Installing/Configuring

Table of Contents


Requirements

PHP: this extension requires PHP 5.4+, version PHP 5.4.4 or never. The required PHP extensions are PCRE (enabled by default), and the memcached extension version 2.0.x.

The mysqlnd_memcache Memcache plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured with mysqlnd support.

For accessing InnoDB tables, this PHP extension requires MySQL Server 5.6.6 or newer with the InnoDB Memcache Daemon Plugin enabled.

For accessing MySQL Cluster NDB tables, this PHP extension requires MySQL Cluster 7.2 or newer with the NDB Memcache API nodes enabled.



Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/mysqlnd_memcache

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_memcache Configure Options
Name Default Changeable Changelog
mysqlnd_memcache.enable 1 PHP_INI_SYSTEM Available since 1.0.0

Here's a short explanation of the configuration directives.

mysqlnd_memcache.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

Note:

This option is mainly used by developers to build this extension statically into PHP. General users are encouraged to build this extension as a shared object, and to unload it completely when it is not needed.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MySQL Memcache Plugin related

MYSQLND_MEMCACHE_DEFAULT_REGEXP (string)
Default regular expression (PCRE style) used for matching SELECT statements that will be mapped into a MySQL Memcache Plugin access point, if possible. It is also possible to use mysqlnd_memcache_set(), but the default approach is using this regular expression for pattern matching.

Assorted

The version number of this plugin can be obtained by using MYSQLND_MEMCACHE_VERSION or MYSQLND_MEMCACHE_VERSION_ID. MYSQLND_MEMCACHE_VERSION is the string representation of the numerical version number MYSQLND_MEMCACHE_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) Example
Major*10000 1*10000 = 10000
Minor*100 0*100 = 0
Patch 0 = 0
MYSQLND_MEMCACHE_VERSION_ID 10000

MYSQLND_MEMCACHE_VERSION (string)
Plugin version string, for example, 1.0.0-alpha.
MYSQLND_MEMCACHE_VERSION_ID (integer)
Plugin version number, for example, 10000.



Mysqlnd_memcache Functions


mysqlnd_memcache_get_config

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_get_configReturns information about the plugin configuration

Description

mysqlnd_memcache_get_config ( mixed $connection ) : array

This function returns an array of all mysqlnd_memcache related configuration information that is attached to the MySQL connection. This includes MySQL, the Memcache object provided via mysqlnd_memcache_set(), and the table mapping configuration that was automatically collected from the MySQL Server.

Parameters

connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

Return Values

An array of mysqlnd_memcache configuration information on success, otherwise FALSE.

The returned array has these elements:

mysqlnd_memcache_get_config() array structure
Array Key Description
memcached Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set(). You can use this to change settings of the memcache connection, or directly by querying the server on this connection.
pattern The PCRE regular expression used to match the SQL query sent to the server. Queries matching this pattern will be further analyzed to decide whether the query can be intercepted and sent via the memcache interface or whether the query is sent using the general MySQL protocol to the server. The pattern is either the default pattern (MYSQLND_MEMCACHE_DEFAULT_REGEXP) or it is set via mysqlnd_memcache_set().
mappings An associative array with a list of all configured containers as they were discovered by this plugin. The key for these elements is the name of the container in the MySQL configuration. The value is described below. The contents of this field is created by querying the MySQL Server during association to MySQL and a memcache connection using mysqlnd_memcache_set().
mapping_query An SQL query used during mysqlnd_memcache_set() to identify the available containers and mappings. The result of that query is provided in the mappings element.
Mapping entry structure
Array Key Description
prefix A prefix used while accessing data via memcache. With the MySQL InnoDB Memcache Deamon plugin, this usually begins with @@ and ends with a configurable separator. This prefix is placed in front of the key value while using the memcache protocol.
schema_name Name of the schema (database) which contains the table being accessed.
table_name Name of the table which contains the data accessible via memcache protocol.
id_field_name Name of the database field (column) with the id used as key when accessing the table via memcache. Often this is the database field having a primary key.
separator The separator used to split the different field values. This is needed as memcache only provides access to a single value while MySQL can map multiple columns to this value.

Note:

The separator, which can be set in the MySQL Server configuration, should not be part of any value retrieved via memcache because proper mapping can't be guaranteed.

fields An array with the name of all fields available for this mapping.

Examples

Example #1 mysqlnd_memcache_get_config() example

<?php
$mysqli 
= new mysqli("host""user""passwd""database");
$memc = new Memcached();
$memc->addServer("host"11211);
mysqlnd_memcache_set($mysqli$memc);

var_dump(mysqlnd_memcache_get_config($mysqli));
?>

The above example will output:

   array(4) {
     ["memcached"]=>
     object(Memcached)#2 (0) {
     }
     ["pattern"]=>
     string(125) "/^\s*SELECT\s*(.+?)\s*FROM\s*`?([a-z0-9_]+)`?\s*WHERE\s*`?([a-z0-9_]+)`?\s*=\s*(?(?=["'])["']([^"']*)["']|([0-9e\.]*))\s*$/is"
     ["mappings"]=>
     array(1) {
       ["mymem_test"]=>
       array(6) {
         ["prefix"]=>
         string(13) "@@mymem_test."
         ["schema_name"]=>
         string(4) "test"
         ["table_name"]=>
         string(10) "mymem_test"
         ["id_field_name"]=>
         string(2) "id"
         ["separator"]=>
         string(1) "|"
         ["fields"]=>
         array(3) {
           [0]=>
           string(2) "f1"
           [1]=>
           string(2) "f2"
           [2]=>
           string(2) "f3"
         }
       }
     }
     ["mapping_query"]=>
     string(209) "    SELECT c.name,
                             CONCAT('@@', c.name, (SELECT value FROM innodb_memcache.config_options WHERE name = 'table_map_delimiter')) AS key_prefix, 
                             c.db_schema, 
                             c.db_table, 
                             c.key_columns, 
                             c.value_columns, 
                             (SELECT value FROM innodb_memcache.config_options WHERE name = 'separator') AS sep 
                        FROM innodb_memcache.containers c"
   }
   

See Also



mysqlnd_memcache_set

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_setAssociate a MySQL connection with a Memcache connection

Description

mysqlnd_memcache_set ( mixed $mysql_connection [, Memcached $memcache_connection [, string $pattern [, callback $callback ]]] ) : bool

Associate mysql_connection with memcache_connection using pattern as a PCRE regular expression, and callback as a notification callback or to unset the association of mysql_connection.

While associating a MySQL connection with a Memcache connection, this function will query the MySQL Server for its configuration. It will automatically detect whether the server is configured to use the InnoDB Memcache Daemon Plugin or MySQL Cluster NDB Memcache support. It will also query the server to automatically identify exported tables and other configuration options. The results of this automatic configuration can be retrieved using mysqlnd_memcache_get_config().

Parameters

mysql_connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

memcache_connection

A Memcached instance with a connection to the MySQL Memcache Daemon plugin. If this parameter is omitted, then mysql_connection will be unassociated from any memcache connection. And if a previous association exists, then it will be replaced.

pattern

A regular expression in Perl Compatible Regular Expression syntax used to identify potential Memcache-queries. The query should have three sub patterns. The first subpattern contains the requested field list, the second the name of the ID column from the query and the third the requested value. If this parameter is omitted or os set to NULL, then a default pattern will be used.

callback

A callback which will be used whenever a query is being sent to MySQL. The callback will receive a single boolean parameter telling if a query was sent via Memcache.

Return Values

TRUE if the association or disassociation is successful, otherwise FALSE if there is an error.

Examples

Example #1 mysqlnd_memcache_set() example with var_dump() as a simple debugging callback.

<?php
$mysqli 
= new mysqli("host""user""passwd""database");
$memc = new Memcached();
$memc->addServer("host"11211);
mysqlnd_memcache_set($mysqli$memcNULL'var_dump');

/* This query will be intercepted and executed via Memcache protocol */
echo "Sending query for id via Memcache: ";
$mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");

/* f1 is not configured as valid key field, this won't be sent via Memcache */
echo "Sending query for f1 via Memcache: ";
$mysqli->query("SELECT id FROM test WHERE f1 = 1");

mysqlnd_memcache_set($mysqli);

/* Now the regular MySQL protocol will be used */
echo "var_dump won't be invoked: ";
$mysqli->query("SELECT f1, f2, f3 WHERE id = 1");

?>

The above example will output:

   Sending query for id via Memcache: bool(true)
   Sending query for f1 via Memcache: bool(false)
   var_dump won't be invoked: 
   

See Also


Table of Contents



Change History

Table of Contents

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.


PECL/mysqlnd_memcache 1.0 series

1.0.0-alpha

The initial release does map basic SQL SELECT statements to a MySQL Memcache plugin access. This bares potential performance benefits as the direct key-value access to MySQL storage using the Memcache protocol is usually faster than using SQL access.






Oracle OCI8


Introduction

These functions allow you to access Oracle Database 19c, 18c, 12c, 11g, 10g, 9i and 8i. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.



Installing/Configuring

Table of Contents


Requirements

The OCI8 1.4 extension is included with PHP 5.3, PHP 5.4 and PHP 5.5. It is also available from » PECL. A newer OCI8 2.0 version is available only from » PECL. OCI8 1.4 requires Oracle 12c, 11g, 10g or 9iR2 client libraries and will install on PHP 4.3.9 onwards. OCI8 2.0 requires Oracle 12c, 11g or 10g client libraries and will install on PHP 5.2 onwards.

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the basic or basiclite Oracle Instant Client ZIP file or RPM package. When building PHP from source code, also install the sdk ZIP file or devel RPM package.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

On Windows, the php_oci8 DLL needs Oracle client libraries from version 10gR2 or greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. The php_oci8_12c DLL from PECL requires Oracle 12cR1 client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

Note:

If OCI8 uses 9iR2 client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 10gR2 client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 12c client libraries, the database can be 10gR2, 11g or 12c.

Note:

Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.



Installation

Configuring PHP with OCI8

Review the previous Requirements section before configuring OCI8.

To enable the OCI8 extension, configure PHP with the option --with-oci8.

Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables must be set before any PHP process starts.

The PHP binary must link with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.

Installing OCI8 as a Shared Extension

The configuration shared option builds OCI8 as a shared library that can be dynamically loaded into PHP. Building a shared extension allows OCI8 to be upgraded easily without impacting the rest of PHP.

Configure OCI8 using one of the following configure options.

  • If using the free » Oracle Instant Client libraries, then do:

       ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib
       

    If Instant Client is installed from ZIP files, make sure to create the library symbolic link first, for example ln -s libclntsh.so.12.1 libclntsh.so.

    If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:

       ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib
       

    For example, --with-oci8=shared,instantclient,/usr/lib/oracle/12.1/client/lib

    Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.

  • If using an Oracle database or full Oracle Client installation then do:

       ./configure --with-oci8=shared,$ORACLE_HOME
       

    Make sure the web server user (nobody, www) has access to the libraries, initialization files and tnsnames.ora (if used) under the $ORACLE_HOME directory. With Oracle 10gR2, you may need to run the $ORACLE_HOME/install/changePerm.sh utility to give directory access.

After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.

To complete installation of OCI8, edit php.ini and add the line:

   extension=oci8.so
   

Installing OCI8 as a Statically Compiled Extension

Configure PHP to include OCI8 using one of the following configure options.

  • If using Oracle Instant Client, then do:

       ./configure --with-oci8=instantclient,/path/to/instant/client/lib
       

  • If using an Oracle database or full Oracle Client installation then do:

       ./configure --with-oci8=$ORACLE_HOME
       

After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.

Installing OCI8 from PECL

The OCI8 extension can be added to an existing PHP installation either automatically or manually from » PECL.

For an automated install follow these steps:

  • If you are behind a firewall, set PEAR's proxy, for example:

       pear config-set http_proxy http://my-proxy.example.com:80/
       

  • Run

       pecl install oci8
       

    When prompted, enter either the value of $ORACLE_HOME, or instantclient,/path/to/instant/client/lib.

    Note: Do not enter the variable $ORACLE_HOME because it will not be expanded. Instead, enter the actual path of the Oracle home directory.

For a manual install when the pecl command is not available, download the PECL OCI8 package, e.g. oci8-1.4.10.tgz.

  • Extract the package:

       tar -zxf oci8-1.4.10.tgz
       cd oci8-1.4.10
       

  • Prepare the package:

       phpize
       

  • Configure the package, either using $ORACLE_HOME or Instant Client

       ./configure -with-oci8=shared,$ORACLE_HOME
       

    or

       ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib
       

  • Install the package:

       make install
       

After either an automatic or manual install, edit your php.ini file and add the line:

   extension=oci8.so
   

Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

Installing OCI8 on Windows

When using Oracle 10gR2 client libraries on Windows, uncomment the php.ini line extension=php_oci8.dll. When using Oracle 11gR2 or later client libraries, uncomment extension=php_oci8_11g.dll or extension=php_oci8.dll. With Oracle 12c libraries use extension=php_oci8_12c.dll or extension=php_oci8_11g.dll or extension=php_oci8.dll. Only one of these DLLs may be enabled at a time. DLLs with higher versions may contain more functionality. Not all DLLs may be available for all versions of PHP. Make sure extension_dir is set to the directory containing the PHP extension DLLs.

If using Instant Client, set the system PATH environment variable to the Oracle library directory.

Setting the Oracle Environment

Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.

Note:

Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.

On Red Hat Linux and variants, export variables at the end of /etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars script in the Apache bin directory. A third option, the Apache SetEnv directive in httpd.conf, may work in some systems but is known to be insufficient in others.

To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.

The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the available variables.
Common Oracle Environment Variables
Name Purpose
ORACLE_HOME Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems.
ORACLE_SID Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect().
LD_LIBRARY_PATH Set this (or its platform equivalent, such as DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/11.1/client/lib. This variable is not needed if the libraries are located by a different search mechanism, such as with ldconfig or with LD_PRELOAD.
NLS_LANG This is the primary variable for setting the character set and globalization information used by the Oracle libraries.
ORA_SDTZ Sets the Oracle session timezone.
TNS_ADMIN Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as localhost/XE. Not needed if the network configuration files are in one of the default locations such as $ORACLE_HOME/network/admin or /etc.
Less frequently used Oracle environment variables include TWO_TASK, ORA_TZFILE, and the various Oracle globalization settings like NLS* and the ORA_NLS_* variables.

Troubleshooting

The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.

While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.

On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.

A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.

Note: If the web server doesn't start or crashes at startup

Check that Apache is linked with the pthread library:

   # ldd /www/apache/bin/httpd
     libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
     libm.so.6 => /lib/libm.so.6 (0x4002f000)
     libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
     libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
     libc.so.6 => /lib/libc.so.6 (0x4007e000)
     /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
   

If the libpthread is not listed, then reinstall Apache:

   # cd /usr/src/apache_1.3.xx
   # make clean
   # LIBS=-lpthread ./config.status
   # make
   # make install
   

Please note that on some systems like UnixWare, it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.



Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the SYSTEM account. Some tests will fail if the test user does not have equivalent permissions.

If Oracle Database Resident Connection Pooling is being tested, set $test_drcp to TRUE and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

       $ export PHP_OCI8_TEST_USER=system
       $ export PHP_OCI8_TEST_PASS=oracle
       $ export PHP_OCI8_TEST_DB=localhost/XE
       $ export PHP_OCI8_TEST_DRCP=FALSE
   
Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. With Oracle 10gR2 XE do:

       $ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh
   

With Oracle 11gR2 XE do:

       $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh
   

For other versions of the Oracle database do:

       $ . /usr/local/bin/oraenv
   

Some shells require that php.ini has E in the variables_order parameter, for example:

       variables_order = "EGPCS"
   

Run all the PHP tests with:

       $ cd your_php_src_directory
       $ make test
   
or run only the OCI8 tests with
       $ cd your_php_src_directory
       $ make test TESTS=ext/oci8
   

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable TEST_TIMEOUT to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database PROCESSES parameter using the following steps:

Connect as the oracle software owner:

       $ su - oracle
   

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase PROCESSES

       $ sqlplus / as sysdba
       SQL> alter system set processes=100 scope=spfile
   

Restart the database:

       SQL> startup force
   



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OCI8 Configuration Options
Name Default Changeable Changelog
oci8.connection_class "" PHP_INI_ALL Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch "100" PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events Off PHP_INI_SYSTEM Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent "-1" PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics Off PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout "-1" PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval "60" PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect Off PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size "20" PHP_INI_SYSTEM Available since PHP 5.1.2 (PECL OCI8 1.1).

Here's a short explanation of the configuration directives.

oci8.connection_class string

This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

The value can be set at runtime with ini_set() prior to connecting.

To use DRCP, OCI8 must be linked with Oracle 11g libraries and the database must be Oracle 11g. The connection pool must be enabled in the database, the oci8.connection_class should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server.

oci8.default_prefetch int

This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of 0 turns off prefetching.

The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

The value can be set per-statement with oci_set_prefetch() prior to statement execution.

In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from 10 to 100.

In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was reduced from 1 to 0, allowing prefetching to be turned off.

When using Oracle Database 12c or later, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

oci8.events boolean

Using On allows PHP to be notified of database Fast Application Notification (FAN) events.

Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

When using On, the database must also be configured to post FAN events.

FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

oci8.old_oci_close_semantics boolean

This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.

oci8.persistent_timeout int

The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that oci8.max_persistent and oci8.persistent_timeout previously attempted to overcome.

Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().

oci8.ping_interval int

The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

oci8.privileged_connect boolean

This option allows connections to use the privileged external credentials OCI_SYSOPER or OCI_SYSDBA.

Note: Seting this On can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

This option is of most use with persistent connections.

When using Oracle Database 12c, this value can be overridden and automatically tuned by Oracle's client oraaccess.xml file. Refer to Oracle documentation for more detail.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

OCI8 Function and Method Modes
Constant Description
OCI_ASSOC Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
OCI_BOTH Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
OCI_COMMIT_ON_SUCCESS Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
OCI_CRED_EXT Used with oci_connect() for using Oracles' External or OS authentication. Introduced in PHP 5.3 and PECL OCI8 1.3.4.
OCI_DEFAULT See OCI_NO_AUTO_COMMIT.
OCI_DESCRIBE_ONLY Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
OCI_EXACT_FETCH Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE Used with OCI-Lob::flush to free buffers used.
OCI_NO_AUTO_COMMIT Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. For readability in new code, use this value instead of the older, equivalent OCI_DEFAULT constant. Introduced in PHP 5.3.2 (PECL OCI8 1.4).
OCI_NUM Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
OCI_RETURN_LOBS Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
OCI_RETURN_NULLS Used with oci_fetch_array() to get empty array elements if the row items value is NULL.
OCI_SEEK_CUR Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_END Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_SET Used with OCI-Lob::seek to set the seek position.
OCI_SYSDATE Obsolete.
OCI_SYSDBA Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_SYSOPER Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_TEMP_BLOB Used with OCI-Lob::writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB Used with OCI-Lob::writeTemporary to indicate that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant Description
OCI_B_BFILE Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN Used with oci_bind_by_name() to bind RAW values.
OCI_B_BLOB Used with oci_bind_by_name() when binding BLOBs.
OCI_B_BOL Used with oci_bind_by_name() to bind a PL/SQL BOOLEAN variable.
OCI_B_CFILEE Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_INT Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_NUM Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
SQLT_BDOUBLE Not supported.
SQLT_BFILEE The same as OCI_B_BFILE.
SQLT_BFLOAT Not supported.
SQLT_BIN The same as OCI_B_BIN.
SQLT_BLOB The same as OCI_B_BLOB.
SQLT_BOL The same as OCI_B_BOL.
SQLT_CFILEE The same as OCI_B_CFILEE.
SQLT_CHR Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB The same as OCI_B_CLOB.
SQLT_FLT Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT The same as OCI_B_INT.
SQLT_LBI Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_NTY The same as OCI_B_NTY.
SQLT_NUM The same as OCI_B_NUM.
SQLT_ODT Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD The same as OCI_B_ROWID.
SQLT_RSET The same as OCI_B_CURSOR.
SQLT_STR Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN Not supported.
SQLT_VCS Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant Description
OCI_DTYPE_FILE This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
OCI_DTYPE_LOB This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
OCI_DTYPE_ROWID This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
OCI_D_FILE The same as OCI_DTYPE_FILE.
OCI_D_LOB The same as OCI_DTYPE_LOB.
OCI_D_ROWID The same as OCI_DTYPE_ROWID.


Examples

These examples connect as the HR user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the XE database on your machine. Change the connect string to your database before running the examples.

Example #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Prepare the statement
$stid oci_parse($conn'SELECT * FROM departments');
if (!
$stid) {
    
$e oci_error($conn);
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Perform the logic of the query
$r oci_execute($stid);
if (!
$r) {
    
$e oci_error($stid);
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Fetch the results of the query
print "<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    print 
"<tr>\n";
    foreach (
$row as $item) {
        print 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    print 
"</tr>\n";
}
print 
"</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');

$id 60;
$data 'Some data';

oci_bind_by_name($stid':myid'$id);
oci_bind_by_name($stid':mydata'$data);

$r oci_execute($stid);  // executes and commits

if ($r) {
    print 
"One row inserted";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding in the WHERE clause of a query

This shows a single scalar bind.

<?php

$conn 
oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid oci_parse($conn$sql);
$didbv 60;
oci_bind_by_name($stid':didbv'$didbv);
oci_execute($stid);
while ((
$row oci_fetch_array($stidOCI_ASSOC)) != false) {
    echo 
$row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Inserting and fetching a CLOB

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

<?php

// Before running, create the table:
//     CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$mykey 12343;  // arbitrary key for this example;

$sql "INSERT INTO mytable (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob"
;

$stid oci_parse($conn$sql);
$clob oci_new_descriptor($connOCI_D_LOB);
oci_bind_by_name($stid":mykey"$mykey5);
oci_bind_by_name($stid":myclob"$clob, -1OCI_B_CLOB);
oci_execute($stidOCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid oci_parse ($conn$query);
oci_bind_by_name($stid":mykey"$mykey5);
oci_execute($stid);

print 
'<table border="1">';
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_LOBS)) {
    print 
'<tr><td>'.$row['MYCLOB'].'</td></tr>';
    
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    
unset($row);  
}
print 
'</table>';

?>

Example #5 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

<?php

/*
  Before running the PHP program, create a stored function in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
  BEGIN
      RETURN p * 3;
  END;

*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p 8;

$stid oci_parse($conn'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid':p'$p);
oci_bind_by_name($stid':r'$r40);

oci_execute($stid);

print 
"$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 8;

$stid oci_parse($conn'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid':p1'$p1);
oci_bind_by_name($stid':p2'$p240);

oci_execute($stid);

print 
"$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 Calling a PL/SQL function that returns a REF CURSOR

Each returned value from the query is a REF CURSOR that can be fetched from.

<?php
/*
  Create the PL/SQL stored function as:

  CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
      rc SYS_REFCURSOR;
  BEGIN
      OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
      RETURN rc;
  END;
*/

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);

echo 
"<table border='1'>\n";
while ((
$row oci_fetch_array($stidOCI_ASSOC))) {
    echo 
"<tr>\n";
    
$rc $row['MFRC'];
    
oci_execute($rc);  // returned column value from the query is a ref cursor
    
while (($rc_row oci_fetch_array($rcOCI_ASSOC))) {   
        echo 
"    <td>" $rc_row['CITY'] . "</td>\n";
    }
    
oci_free_statement($rc);
    echo 
"</tr>\n";
}
echo 
"</table>\n";

// Output is:
//   Beijing
//   Bern
//   Bombay
//   Geneva

oci_free_statement($stid);
oci_close($conn);

?>


OCI8 Connection Handling and Connection Pooling

Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle Database Resident Connection Pooling (in Oracle Database 11g or later), or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FCGI, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

DRCP Connection Pooling

PHP from 5.3 (PECL OCI8 1.3) supports Oracle Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default Dedicated database server processes, or use Shared servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g or greater.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, build PHP with the OCI8 1.3 (or later) extension and Oracle 11g (or later) libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

           SQL> execute dbms_connection_pool.start_pool;
       

  • Optionally use dbms_connection_pool.alter_param() to configure DRCP settings. The current pool settings can be queried from the DBA_CPOOL_INFO view.

  • Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like MYDB:

           $c = oci_pconnect("myuser", "mypassword", "MYDB");
       

    modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for example:

           MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
                  (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
                  (SERVER=POOLED)))
       

    Alternatively, modify the Easy Connect syntax in PHP and add :POOLED after the service name:

           $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");
       

  • Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

           oci8.connection_class = "MY_APPLICATION_NAME"
       

  • Run the application, connecting to the 11g (or later) database.

Note:

Applications using Oracle 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle Shared servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

DRCP Recommendations and Known Limitations

Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

From OCI8 1.3, persistent connections can be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:

  • Connect using Oracle Dedicated or Shared servers instead of DRCP.
  • Set PHP's oci8.statement_cache_size to 0.
  • Set an event in the database initialization parameter file: event="56699 trace name context forever, level 128".

Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle bug 6474441 allow PHP applications with DRCP connection to use a database LOGON trigger to set session properties at the time of session creation. Examples of such settings are the NLS language and the date format.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following workarounds can be used instead of using LOGON triggers:

  • After logon, explicitly set the session properties using PHP application code.
  • Connect using Oracle Dedicated or Shared servers instead of DRCP.

The automatic re-establishment of PHP persistent connections after an Apache or FCGI process respawns means LOGON triggers in PHP are only recommended for setting session attributes and not for per-application user connection requests. This is even more so with DRCP due to the automatic pool sizing and with the way LOGON triggers fire with DRCP authentication.



OCI8 Fast Application Notification (FAN) Support

FAN support gives fast connection failover, an Oracle Database high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or later.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP OCI8, build PHP OCI8 with Oracle 10gR2 or later libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

           SQL> execute dbms_service.modify_service(
                          SERVICE_NAME        => 'sales',
                          AQ_HA_NOTIFICATIONS => TRUE);
       

  • Edit php.ini and add

           oci8.events = On
       

  • If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
  • Run the application, connecting to Oracle Database 10gR2 or later.



OCI8 Transparent Application Failover (TAF) Support

TAF is an Oracle Database feature that provides high availability. It enables PHP OCI8 applications to automatically reconnect to a preconfigured database when database connectivity fails due to instance or network failure.

In a configured Oracle Database system, TAF occurs when the PHP application detects that the database instance is down or unreachable. It establishes a connection to another node in an Oracle » RAC configuration, a hot standby database, or the same database instance itself. See » Oracle Call Interface Programmer's Guide for more information about OCI TAF.

An application callback can be registered with oci_register_taf_callback(). During failover, normal application processing stops and the registered callback is invoked. The callback notifies the application of the failover events. If the failover succeeds, normal processing will be resumed. If the failover aborts, any following database operations in the application will fail due to no connection being available.

When a connection fails over to another database, the callback can reset any necessary connection state, for example replaying any necessary ALTER SESSION commands if the database service did not have -failover_restore enabled.

An application callback can be removed by calling oci_unregister_taf_callback().

Configuring Transparent Application Failover

TAF can be configured on the PHP OCI8 side or in the database configuration. If both are configured, database-side settings take precedence.

Configure TAF in PHP OCI8 (the client side) by including the FAILOVER_MODE parameter in the CONNECT_DATA portion of a connect descriptor. See Configuring Transparent Application Failover in »  Oracle Database Net Services Administrator's Guide for more information about client side configuration of TAF.

An example tnsnames.ora to configure TAF reconnecting to the same database instance:

       ORCL =
         (DESCRIPTION =
           (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
           (CONNECT_DATA =
             (SERVICE_NAME = orclpdb1)
             (FAILOVER_MODE =
               (TYPE = SELECT)
               (METHOD = BASIC)
               (RETRIES = 20)
               (DELAY = 15))))
    

Alternatively configure TAF on the database side by modifying the target service with » srvctl (for RAC) or the »  DBMS_SERVICE.MODIFY_SERVICE packaged procedure (for single instance databases).

Using TAF Callbacks in OCI8

A TAF callback is an application function that can be registered to be called during failover. It is called several times while re-establishing the application's connection.

Callback first occurs when a loss of connection is detected. This allows the application to act accordingly for the upcoming delay of the failover. If the failover is successful, the callback is invoked after connection is re-established and usable. At this time, the application can resynchronize session settings and take actions such as informing the user that failover occurred. If failover is unsuccessful, a callback occurs to inform the application that a failover did not take place and the connection is unusable.

The interface of a TAF user-defined callback function is as follows:

userCallbackFn ( resource $connection , int $event , int $type ) : int

connection

The Oracle connection on which the TAF callback was registered via oci_register_taf_callback(). The connection is not valid until the failover completes successfully.

event

The failover event indicates the current status of the failover.

  • OCI_FO_BEGIN indicates that failover has detected a lost connection and failover is starting.

  • OCI_FO_END indicates successful completion of failover.

  • OCI_FO_ABORT indicates that failover was unsuccessful, and there is no option of retrying.

  • OCI_FO_ERROR also indicates that failover was unsuccessful, but it gives the application the opportunity to handle the error and return OCI_FO_RETRY to retry failover.

  • OCI_FO_REAUTH indicates that an Oracle user has been re-authenticated.

type

The failover type. This lets the callback know what type of failover the application has requested. The usual values are as follows:

  • OCI_FO_SESSION indicates that the user has requested only session failover. For example, if a user's connection is lost, then a new session is automatically created for the user on the backup. This type of failover does not attempt to recover SELECTs.

  • OCI_FO_SELECT indicates that the user has requested SELECT failover as well. It allows users with open cursors to continue fetching from them after failure.

return value

  • 0 indicates the failover steps should continue normally.

  • OCI_FO_RETRY indicates that the failover should be attempted again by Oracle. In case of an error while failing over to a new connection, TAF is able to retry the failover. Typically, the application code should sleep for a while before returning OCI_FO_RETRY.

The following example registers a TAF callback

<?php

// Define userspace callback
class MyClass {
    public static 
$retry_count;
    public static function 
TAFCallback($conn$event$type)
    {
        switch (
$event) {
            case 
OCI_FO_BEGIN:
                
printf(" Failing Over ... Please stand by\n");
                
printf(" Failover type was found to be %s \n",
                       ((
$type==OCI_FO_SESSION) ? "SESSION"
                        
:(($type==OCI_FO_SELECT) ? "SELECT" "UNKNOWN!")));
                
self::$retry_count 0;
                break;
            case 
OCI_FO_ABORT:
                
// The application cannot continue using the database
                
printf(" Failover aborted. Failover will not take place.\n");
                break;
            case 
OCI_FO_END:
                
// Failover completes successfully. Inform users a failover occurs.
                
printf(" Failover ended ... resuming services\n");
                break;
            case 
OCI_FO_REAUTH:
                
printf(" Failed over user ... resuming services\n");
                
// Replay any ALTER SESSION commands associated with this connection
                // eg. oci_parse($conn, ‘ALTER SESSION …’) ;
                
break;
            case 
OCI_FO_ERROR:
                
// Stop retrying if we have already attempted for 20 times.
                
if (self::$retry_count >= 20)
                    return 
0;
                
printf(" Failover error received. Sleeping...\n");
                
sleep(10);
                
self::$retry_count++;
                return 
OCI_FO_RETRY// retry failover
                
break;
            default:
                
printf("Bad Failover Event: %d.\n"$event);
                break;
        }
        return 
0;
    }
}

$fn_name 'MyClass::TAFCallback';

$conn oci_connect('hr''welcome''orcl');
$sysconn oci_connect('system''oracle''orcl');

// Use a privileged connection to construct a SQL statement that will initiate failover
$sql = <<< 'END'
select unique 'alter system disconnect session '''||sid||','||serial#||''''
from v$session_connect_info
where sid = sys_context('USERENV', 'SID')
END;

$s oci_parse($conn$sql);
oci_execute($s);
$r oci_fetch_array($s);
$disconnectssql $r[0];

oci_register_taf_callback($conn$fn_name); // Register TAFCallback to Oracle TAF

print("Parsing user query\n");
$sql "select systimestamp from dual";
$stmt oci_parse($conn$sql);

// For example, if a connection loss occurs at this point, oci_execute() will
// detect the loss and failover begins. During failover, oci_execute() will
// invoke the TAF callback function several times. If the failover is successful,
// a new connection is transparently created and oci_execute() will continue as
// usual. The connection session settings can be reset in the TAF callback
// function. If the failover is aborted, oci_execute() will return an error
// because a valid connection is not available.

// Disconnect the user, which initiates failover
print("Disconnecting the user\n");
$discsql oci_parse($sysconn$disconnectssql);
oci_execute($discsql);

print(
"Executing user query\n");
$e oci_execute($stmt);
if (!
$e) {
    
$m oci_error($stmt);
    
trigger_error("Could not execute statement: "$m['message'], E_USER_ERROR);
}
$row oci_fetch_array($stmt);
print(
$row[0] . "\n");

// do other SQL statements with the new connection, if it is valid
// $stmt = oci_parse($conn,  . . .);

?>


OCI8 and DTrace Dynamic Tracing

OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.

Installing OCI8 with DTrace Support

To enable DTrace support in PHP OCI8, build OCI8 as a shared extension after setting PHP_DTRACE.

   $ export PHP_DTRACE=yes
   $ pecl install oci8
   

Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:

   extension=oci8.so
   

If you install PHP OCI8 2.0 from PECL using phpize and configure (instead of pecl), you will still need to set PHP_DTRACE=yes. This is because the --enable-dtrace option will be ignored by the limited configure script of a PECL bundle.

See Installation of PECL extensions for general PECL installation instructions.

DTrace Static Probes in PHP OCI8

The following static probes are available in PHP OCI8
Probe Name Probe Description Probe Arguments
oci8-connect-entry Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive
oci8-connect-return Fires at the end of connection. void *connection
oci8-check-connection Fires if an Oracle error might have caused the connection to become invalid. void *connection, char *client_id, int is_open, long errcode, unsigned long server_status
oci8-sqltext Fires when oci_parse() is executed. void *connection, char *client_id, void *statement, char *sql
oci8-connection-close Fires when the connection to the database is completely destroyed. void *connection
oci8-error Fires if an Oracle error occurs. int status, long errcode
oci8-execute-mode Fires at oci_execute() to show the execution mode. void *connection, char *client_id, void *statement, unsigned int mode

These probes are useful for tracing OCI8 scripts.

The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.

The client_id is the value set by oci_set_client_identifier().

Core PHP also has static probes. See DTrace Static Probes in Core PHP.

Internal Debugging DTrace Probes in OCI8
Probe Name
oci8-connect-expiry
oci8-connect-lookup
oci8-connect-p-dtor-close
oci8-connect-p-dtor-release
oci8-connect-type
oci8-sesspool-create
oci8-sesspool-stats
oci8-sesspool-type

These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.

Listing DTrace Static Probes in PHP OCI8

To list available probes, start a PHP process and then run:

   # dtrace -l
   

The output will be similar to:

      ID   PROVIDER            MODULE                          FUNCTION NAME
      [ . . . ]
      17 phpoci22116           oci8.so   php_oci_dtrace_check_connection oci8-check-connection
      18 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-entry
      19 phpoci22116           oci8.so         php_oci_persistent_helper oci8-connect-expiry
      20 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-lookup
      21 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
      22 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
      23 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-return
      24 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-type
      25 phpoci22116           oci8.so          php_oci_connection_close oci8-connection-close
      26 phpoci22116           oci8.so                     php_oci_error oci8-error
      27 phpoci22116           oci8.so         php_oci_statement_execute oci8-execute-mode
      28 phpoci22116           oci8.so              php_oci_create_spool oci8-sesspool-create
      29 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-stats
      30 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-type
      31 phpoci22116           oci8.so          php_oci_statement_create oci8-sqltext
   

The Provider column values consist of phpoci and the process id of the currently running PHP process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP OCI8 Example

This example shows the basics of the DTrace D scripting language.

Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace

   #!/usr/sbin/dtrace -Zs
   
   #pragma D option quiet
   
   php*:::oci8-connect-entry
   {
       printf("%lld: PHP connect-entry\n", walltimestamp);
       printf("  credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
       printf("  charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
       printf("  session_mode=%ld\n", (long)arg3);
       printf("  persistent=%d\n", (int)arg4);
       printf("  exclusive=%d\n", (int)arg5);
   }
   
   php*:::oci8-connect-return
   {
       printf("%lld: PHP oci8-connect-return\n", walltimestamp);
       printf("  connection=0x%p\n", (void *)arg0);
   }
   
   php*:::oci8-connection-close
   {
       printf("%lld: PHP oci8-connect-close\n", walltimestamp);
       printf("  connection=0x%p\n", (void *)arg0);
   }
   
   php*:::oci8-error
   {
       printf("%lld: PHP oci8-error\n", walltimestamp);
       printf("  status=%d\n", (int)arg0);
       printf("  errcode=%ld\n", (long)arg1);
   }
   
   php*:::oci8-check-connection
   {
       printf("%lld: PHP oci8-check-connection\n", walltimestamp);
       printf("  connection=0x%p\n", (void *)arg0);
       printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
       printf("  is_open=%d\n", arg2);
       printf("  errcode=%ld\n", (long)arg3);
       printf("  server_status=%lu\n", (unsigned long)arg4);
   }
   
   php*:::oci8-sqltext
   {
       printf("%lld: PHP oci8-sqltext\n", walltimestamp);
       printf("  connection=0x%p\n", (void *)arg0);
       printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
       printf("  statement=0x%p\n", (void *)arg2);
       printf("  sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
   }
   
   php*:::oci8-execute-mode
   {
       printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
       printf("  connection=0x%p\n", (void *)arg0);
       printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
       printf("  statement=0x%p\n", (void *)arg2);
       printf("  mode=0x%x\n", arg3);
   }
   

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate when no PHP executable was running because it knows none of the probes to be monitored are in existence.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps helps reduce confusion.

The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:

   # ./user_oci8_probes.d
   

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:

   1381794982092854582: PHP connect-entry
     credentials="hr@localhost/pdborcl"
     charset=""
     session_mode=0
     persistent=0
     exclusive=0
   1381794982183158766: PHP oci8-connect-return
     connection=0x7f4a7907bfb8
   1381794982183594576: PHP oci8-sqltext
     connection=0x7f4a7907bfb8
     client_id="Chris"
     statement=0x7f4a7907c2a0
     sql="select * from employees"
   1381794982183783706: PHP oci8-execute-mode
     connection=0x7f4a7907bfb8
     client_id="Chris"
     statement=0x7f4a7907c2a0
     mode=0x20
   1381794982444344390: PHP oci8-connect-close
     connection=0x7f4a7907bfb8
   

When monitoring is complete, the D script can be terminated with a ^C.



Supported Datatypes

The driver supports the following types when binding parameters using the oci_bind_by_name() function:
Type Mapping
SQLT_NTY Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_BOL Bind the PHP parameter to a PL/SQL BOOLEAN
SQLT_CHR and any other type Converts the PHP parameter to a string type and binds as a string.
The following types are supported when retrieving columns from a result set:
Type Mapping
SQLT_RSET Creates an oci statement resource to represent the cursor.
SQLT_RDD Creates a ROWID object.
SQLT_BLOB Creates a LOB object.
SQLT_CLOB Creates a LOB object.
SQLT_BFILE Creates a LOB object.
SQLT_LNG Bound as SQLT_CHR, returned as a string
SQLT_LBI Bound as SQLT_BIN, returned as a string
Any other type Bound as SQLT_CHR, returned as a string


OCI8 Functions


oci_bind_array_by_name

(PHP 5 >= 5.1.2, PHP 7, PECL OCI8 >= 1.2.0)

oci_bind_array_by_nameBinds a PHP array to an Oracle PL/SQL array parameter

Description

oci_bind_array_by_name ( resource $statement , string $name , array &$var_array , int $max_table_length [, int $max_item_length = -1 [, int $type = SQLT_AFC ]] ) : bool

Binds the PHP array var_array to the Oracle placeholder name, which points to an Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

Parameters

statement

A valid OCI statement identifier.

name

The Oracle placeholder.

var_array

An array.

max_table_length

Sets the maximum length both for incoming and result arrays.

max_item_length

Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will find the longest element in the incoming array and will use it as the maximum length.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_bind_array_by_name() example

<?php

$conn 
oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$create "CREATE TABLE bind_example(name VARCHAR(20))";
$stid oci_parse($conn$create);
oci_execute($stid);

$create_pkg "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;"
;
$stid oci_parse($conn$create_pkg);
oci_execute($stid);

$create_pkg_body "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    -- Bulk Insert
    FORALL i IN INDICES OF c1
      INSERT INTO bind_example VALUES (c1(i));

    -- Fetch and reverse
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;"
;
$stid oci_parse($conn$create_pkg_body);
oci_execute($stid);

$stid oci_parse($conn"BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one""two""three""four""five");
oci_bind_array_by_name($stid":c1"$array5, -1SQLT_CHR);
oci_execute($stid);

var_dump($array);

?>



oci_bind_by_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_bind_by_nameBinds a PHP variable to an Oracle placeholder

Description

oci_bind_by_name ( resource $statement , string $bv_name , mixed &$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] ) : bool

Binds a PHP variable variable to the Oracle bind variable placeholder bv_name. Binding is important for Oracle database performance and also as a way to avoid SQL Injection security issues.

Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.

PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.

In Oracle, bind variables are commonly divided into IN binds for values that are passed into the database, and OUT binds for values that are returned to PHP. A bind variable may be both IN and OUT. Whether a bind variable will be used for input or output is determined at run-time.

You must specify maxlength when using an OUT bind so that PHP allocates enough memory to hold the returned value.

For IN binds it is recommended to set the maxlength length if the statement is re-executed multiple times with different values for the PHP variable. Otherwise Oracle may truncate data to the length of the initial PHP variable value. If you don't know what the maximum length will be, then re-call oci_bind_by_name() with the current data size prior to each oci_execute() call. Binding an unnecessarily large length will have an impact on process memory in the database.

A bind call tells Oracle which memory address to read data from. For IN binds that address needs to contain valid data when oci_execute() is called. This means that the variable bound must remain in scope until execution. If it doesn't, unexpected results or errors such as "ORA-01460: unimplemented or unreasonable conversion requested" may occur. For OUT binds one symptom is no value being set in the PHP variable.

For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.

Parameters

statement

A valid OCI8 statement identifer.

bv_name

The colon-prefixed bind variable placeholder used in the statement. The colon is optional in bv_name. Oracle does not use question marks for placeholders.

variable

The PHP variable to be associated with bv_name

maxlength

Sets the maximum length for the data. If you set it to -1, this function will use the current length of variable to set the maximum length. In this case the variable must exist and contain data when oci_bind_by_name() is called.

type

The datatype that Oracle will treat the data as. The default type used is SQLT_CHR. Oracle will convert the data between this type and the database column (or PL/SQL variable type), when possible.

If you need to bind an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using the oci_new_descriptor() function. The length is not used for abstract datatypes and should be set to -1.

Possible values for type are:

  • SQLT_BFILEE or OCI_B_BFILE - for BFILEs;

  • SQLT_CFILEE or OCI_B_CFILEE - for CFILEs;

  • SQLT_CLOB or OCI_B_CLOB - for CLOBs;

  • SQLT_BLOB or OCI_B_BLOB - for BLOBs;

  • SQLT_RDD or OCI_B_ROWID - for ROWIDs;

  • SQLT_NTY or OCI_B_NTY - for named datatypes;

  • SQLT_INT or OCI_B_INT - for integers;

  • SQLT_CHR - for VARCHARs;

  • SQLT_BIN or OCI_B_BIN - for RAW columns;

  • SQLT_LNG - for LONG columns;

  • SQLT_LBI - for LONG RAW columns;

  • SQLT_RSET - for cursors created with oci_new_cursor();

  • SQLT_BOL or OCI_B_BOL - for PL/SQL BOOLEANs (Requires OCI8 2.0.7 and Oracle Database 12c)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Inserting data with oci_bind_by_name()

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");

$id 1;
$text "Data to insert     ";
oci_bind_by_name($stid":id_bv"$id);
oci_bind_by_name($stid":text_bv"$text);
oci_execute($stid);

// Table now contains: 1, 'Data to insert     '

?>

Example #2 Binding once for multiple executions

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER);

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$a = array(1,3,5,7,11);  // data to insert

$stid oci_parse($conn'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid':bv'$v20);
foreach (
$a as $v) {
    
$r oci_execute($stidOCI_DEFAULT);  // don't auto commit
}
oci_commit($conn); // commit everything at once

// Table contains five rows: 1, 3, 5, 7, 11

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding with a foreach() loop

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid oci_parse($conn$sql);

$ba = array(':dname' => 'IT Support'':loc' => 1700);

foreach (
$ba as $key => $val) {

    
// oci_bind_by_name($stid, $key, $val) does not work
    // because it binds each placeholder to the same location: $val
    // instead use the actual location of the data: $ba[$key]
    
oci_bind_by_name($stid$key$ba[$key]);
}

oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS);
foreach (
$row as $item) {
    print 
$item."<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Binding in a WHERE clause

<?php

$conn 
oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid oci_parse($conn$sql);
$didbv 60;
oci_bind_by_name($stid':didbv'$didbv);
oci_execute($stid);
while ((
$row oci_fetch_array($stidOCI_ASSOC)) != false) {
    echo 
$row['LAST_NAME'] ."<br>\n";
}

// Output is
//    Austin
//    Ernst
//    Hunold
//    Lorentz
//    Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #5 Binding with a LIKE clause

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that begin with 'South'
$stid oci_parse($conn"SELECT city FROM locations WHERE city LIKE :bv");
$city 'South%';  // '%' is a wildcard in SQL
oci_bind_by_name($stid":bv"$city);
oci_execute($stid);
oci_fetch_all($stid$res);

foreach (
$res['CITY'] as $c) {
    print 
$c "<br>\n";
}
// Output is
//   South Brunswick
//   South San Francisco
//   Southlake

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Binding with REGEXP_LIKE

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that contain 'ing'
$stid oci_parse($conn"SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city '.*ing.*';
oci_bind_by_name($stid":bv"$city);
oci_execute($stid);
oci_fetch_all($stid$res);

foreach (
$res['CITY'] as $c) {
    print 
$c "<br>\n";
}
// Output is
//   Beijing
//   Singapore

oci_free_statement($stid);
oci_close($conn);

?>

For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.

Example #7 Binding Multiple Values in an IN Clause

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid oci_parse($conn$sql);
$mye1 103;
$mye2 104;
$mye3 NULL// pretend we were not given this value
oci_bind_by_name($stid':e1'$mye1);
oci_bind_by_name($stid':e2'$mye2);
oci_bind_by_name($stid':e3'$mye3);
oci_execute($stid);
oci_fetch_all($stid$res);
foreach (
$res['LAST_NAME'] as $name) {
    print 
$name ."<br>\n";
}

// Output is
//   Ernst
//   Hunold

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 Binding a ROWID returned by a query

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//   INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
//   COMMIT;

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id 1;
oci_bind_by_name($stid':id_bv'$id);
oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS);
$rid $row['ROWID'];
$name $row['NAME'];

// Change name to upper case & save the changes
$name strtoupper($name);
$stid oci_parse($conn'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid':n_bv'$name);
oci_bind_by_name($stid':r_bv'$rid, -1OCI_B_ROWID);
oci_execute($stid);

// The table now contains 1, 100, CHRIS

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 Binding a ROWID on INSERT

<?php

// This example inserts an id & name, and then updates the salary
// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
        RETURNING ROWID INTO :rid"
;

$ins_stid oci_parse($conn$sql);

$rowid oci_new_descriptor($connOCI_D_ROWID);
oci_bind_by_name($ins_stid":id_bv",   $id,    10);
oci_bind_by_name($ins_stid":name_bv"$name,  32);
oci_bind_by_name($ins_stid":rid",     $rowid, -1OCI_B_ROWID);

$sql "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid oci_parse($conn$sql);
oci_bind_by_name($upd_stid":rid"$rowid, -1OCI_B_ROWID);
oci_bind_by_name($upd_stid":salary"$salary,   32);

// ids and names to insert
$data = array(1111 => "Larry",
              
2222 => "Bill",
              
3333 => "Jim");

// Salary of each person
$salary 10000;

// Insert and immediately update each row
foreach ($data as $id => $name) {
    
oci_execute($ins_stid);
    
oci_execute($upd_stid);
}

$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);

// Show the new rows
$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stid);
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    
var_dump($row);
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Binding for a PL/SQL stored function

<?php

//  Before running the PHP program, create a stored function in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
//  BEGIN
//      RETURN p * 3;
//  END;

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p 8;

$stid oci_parse($conn'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid':p'$p);

// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid':r'$r40);

oci_execute($stid);

print 
"$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 Binding parameters for a PL/SQL stored procedure

<?php

//  Before running the PHP program, create a stored procedure in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
//  BEGIN
//      p2 := p1 * 2;
//  END;

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p1 8;

$stid oci_parse($conn'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid':p1'$p1);

// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid':p2'$p240);

oci_execute($stid);

print 
"$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #12 Binding a CLOB column

<?php

// Before running, create the table:
//     CREATE TABLE mytab (mykey NUMBER, myclob CLOB);

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$mykey 12343;  // arbitrary key for this example;

$sql "INSERT INTO mytab (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob"
;

$stid oci_parse($conn$sql);
$clob oci_new_descriptor($connOCI_D_LOB);
oci_bind_by_name($stid":mykey"$mykey5);
oci_bind_by_name($stid":myclob"$clob, -1OCI_B_CLOB);
oci_execute($stidOCI_DEFAULT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query 'SELECT myclob FROM mytab WHERE mykey = :mykey';

$stid oci_parse ($conn$query);
oci_bind_by_name($stid":mykey"$mykey5);
oci_execute($stid);

print 
'<table border="1">';
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_LOBS)) {
    print 
'<tr><td>'.$row['MYCLOB'].'</td></tr>';
    
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    
unset($row);  
}
print 
'</table>';

?>

Example #13 Binding a PL/SQL BOOLEAN

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$plsql 
  
"begin
    :output1 := true;
    :output2 := false;
   end;"
;

$s oci_parse($c$plsql);
oci_bind_by_name($s':output1'$output1, -1OCI_B_BOL);
oci_bind_by_name($s':output2'$output2, -1OCI_B_BOL);
oci_execute($s);
var_dump($output1);  // true
var_dump($output2);  // false

?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name() simultaneously as no quoting is needed. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.

Note:

If you bind a string to a CHAR column in a WHERE clause, remember that Oracle uses blank-padded comparison semantics for CHAR columns. Your PHP variable should be blank padded to the same width as the column for the WHERE clause to succeed.

Note:

The PHP variable argument is a reference. Some forms of loops do not work as expected:

<?php
foreach ($myarray as $key => $value)  {
    
oci_bind_by_name($stid$key$value);
}
?>

This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:

<?php
foreach ($myarray as $key => $value) {
    
oci_bind_by_name($stid$key$myarray[$key]);
}
?>

See Also



oci_cancel

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_cancelCancels reading from cursor

Description

oci_cancel ( resource $statement ) : bool

Invalidates a cursor, freeing all associated resources and cancels the ability to read from it.

Parameters

statement

An OCI statement.

Return Values

Returns TRUE on success or FALSE on failure.



oci_client_version

(PHP 5 >= 5.3.7, PHP 7, PECL OCI8 >= 1.4.6)

oci_client_versionReturns the Oracle client library version

Description

oci_client_version ( void ) : string

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

Parameters

None

Return Values

Returns the version number as a string.

Examples

Example #1 oci_client_version() example

<?php
    
echo "Client Version: " oci_client_version(); // Client version: 11.2.0.2
?>

Notes

Note:

Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.

See Also



oci_close

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_closeCloses an Oracle connection

Description

oci_close ( resource $connection ) : bool

Unsets connection. The underlying database connection is closed if no other resources are using it and if it was created with oci_connect() or oci_new_connect().

It is recommended to close connections that are no longer needed because this makes database resources available for other users.

Parameters

connection

An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a connection

Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM departments');
$r oci_execute($stid);
oci_fetch_all($stid$res);
var_dump($res);

// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Database connections are not closed until all references are closed

The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM departments');  // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid$res);
var_dump($res);

oci_close($conn);

// $conn is no longer usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn);  // prints NULL  

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);

// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);  

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);

?>

Example #3 Closing a connection opened more than once

When database credentials are reused, both connections must be closed before the underlying database connection is closed.

<?php

$conn1 
oci_connect('hr''welcome''localhost/XE');

// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 oci_connect('hr''welcome''localhost/XE');

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);

oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1);  // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2);  // displays that $conn2 is still a valid connection resource

?>

Example #4 Connections are closed when variables go out of scope

When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.

<?php

function myfunc() {
    
$conn oci_connect('hr''hrpwd''localhost/XE');
    if (!
$conn) {
        
$e oci_error();
        
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    
$stid oci_parse($conn'UPDATE mytab SET id = 100');
    
oci_execute($stidOCI_NO_AUTO_COMMIT);
    return 
"Finished";
}

$r myfunc();
// At this point a rollback occurred and the underlying database connection was released.

print $r;  // displays the function return value "Finished"

?>

Notes

Note:

Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.

Note:

Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.

Note:

The oci_close() function does not close the underlying database connections created with oci_pconnect().

See Also



oci_commit

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_commitCommits the outstanding database transaction

Description

oci_commit ( resource $connection ) : bool

Commits the outstanding transaction for the Oracle connection. A commit ends the current transaction and makes permanent all changes. It releases all locks held.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_commit() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn"INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r oci_execute($stidOCI_NO_AUTO_COMMIT);
if (!
$r) {    
    
$e oci_error($stid);
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid oci_parse($conn'INSERT INTO myschedule (startday) VALUES (12)');
$r oci_execute($stidOCI_NO_AUTO_COMMIT);
if (!
$r) {    
    
$e oci_error($stid);
    
oci_rollback($conn);  // rollback changes to both tables
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r oci_commit($conn);
if (!
$r) {
    
$e oci_error($conn);
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Notes

Note:

Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

See Also



oci_connect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_connectConnect to an Oracle database

Description

oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] ) : resource

Returns a connection identifier needed for most other OCI8 operations.

See Connection Handling for general information on connection management and connection pooling.

From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.

The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.

Parameters

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example #1 Basic oci_connect() using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

Example #2 Basic oci_connect() using a Network Connect name

<?php

// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
//   MYDB =
//     (DESCRIPTION =
//       (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
//       (CONNECT_DATA =
//         (SERVER = DEDICATED)
//         (SERVICE_NAME = XE)
//       )
//     )

$conn oci_connect('hr''welcome''MYDB');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

Example #3 oci_connect() with an explicit character set

<?php

$conn 
oci_connect('hr''welcome''localhost/XE''AL32UTF8');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

Example #4 Using multiple calls to oci_connect()

<?php

$c1 
oci_connect("hr""welcome"'localhost/XE');
$c2 oci_connect("hr""welcome"'localhost/XE');

// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo 
"c2 is $c2<br>\n";

function 
create_table($conn)
{
    
$stmt oci_parse($conn"create table hallo (test varchar2(64))");
    
oci_execute($stmt);
    echo 
"Created table<br>\n";
}

function 
drop_table($conn)
{
    
$stmt oci_parse($conn"drop table hallo");
    
oci_execute($stmt);
    echo 
"Dropped table<br>\n";
}

function 
insert_data($connname$conn)
{
    
$stmt oci_parse($conn"insert into hallo
              values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))"
);
    
oci_execute($stmtOCI_DEFAULT);
    echo 
"$connname inserted row without committing<br>\n";
}

function 
rollback($connname$conn)
{
    
oci_rollback($conn);
    echo 
"$connname rollback<br>\n";
}

function 
select_data($connname$conn)
{
    
$stmt oci_parse($conn"select * from hallo");
    
oci_execute($stmtOCI_DEFAULT);
    echo 
"$connname ----selecting<br>\n";
    while (
oci_fetch($stmt)) {
        echo 
"    " oci_result($stmt"TEST") . "<br>\n";
    }
    echo 
"$connname ----done<br>\n";
}

create_table($c1);

insert_data('c1'$c1);   // Insert a row using c1
sleep(2);                 // sleep to show a different timestamp for the 2nd row
insert_data('c2'$c2);   // Insert a row using c2

select_data('c1'$c1);   // Results of both inserts are returned
select_data('c2'$c2);   // Results of both inserts are returned

rollback('c1'$c1);      // Rollback using c1

select_data('c1'$c1);   // Both inserts have been rolled back
select_data('c2'$c2);

drop_table($c1);

// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo 
"c1 is $c1<br>\n";
echo 
"c2 is $c2<br>\n";


// Output is:
//    c1 is Resource id #5
//    c2 is Resource id #5
//    Created table
//    c1 inserted row without committing
//    c2 inserted row without committing
//    c1 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c1 ----done
//    c2 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c2 ----done
//    c1 rollback
//    c1 ----selecting
//    c1 ----done
//    c2 ----selecting
//    c2 ----done
//    Dropped table
//    c1 is 
//    c2 is Resource id #5

?>

Notes

Note:

An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

See Also



oci_define_by_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_define_by_nameAssociates a PHP variable with a column for query fetches

Description

oci_define_by_name ( resource $statement , string $column_name , mixed &$variable [, int $type = SQLT_CHR ] ) : bool

Associates a PHP variable with a column for query fetches using oci_fetch().

The oci_define_by_name() call must occur before executing oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

column_name

The column name used in the query.

Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.

variable

The PHP variable that will contain the returned column value.

type

The data type to be returned. Generally not needed. Note that Oracle-style data conversions are not performed. For example, SQLT_INT will be ignored and the returned data type will still be SQLT_CHR.

You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_define_by_name() example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid oci_parse($conn$sql);

// The defines MUST be done before executing
oci_define_by_name($stid'LOCATION_ID'$locid);
oci_define_by_name($stid'CITY'$city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo 
"Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_define_by_name() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM mytab');

// Use uppercase for non case-sensitive column names
oci_define_by_name($stid'ID'$id);

// Use the exact case for case-sensitive column names
oci_define_by_name($stid'MyDescription'$mydesc);

oci_execute($stid);

while (
oci_fetch($stid)) {
    echo 
"id $id is $mydesc<br>\n";
}

// Displays:
//   id 1 is Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_define_by_name() with LOB columns

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid'ID'$id);
oci_define_by_name($stid'FRUIT'$fruit);  // $fruit will become a LOB descriptor

oci_execute($stid);

while (
oci_fetch($stid)) {
    echo 
$id " is " $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_define_by_name() with an explicit type

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid'ID'$id);

$fruit oci_new_descriptor($connOCI_D_LOB);
oci_define_by_name($stid'FRUIT'$fruitOCI_D_CLOB);

oci_execute($stid);

while (
oci_fetch($stid)) {
    echo 
$id " is " $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

See Also



oci_error

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_errorReturns the last error found

Description

oci_error ([ resource $resource ] ) : array

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

Parameters

resource

For most errors, resource is the resource handle that was passed to the failing function call. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect() do not pass resource.

Return Values

If no error is found, oci_error() returns FALSE. Otherwise, oci_error() returns the error information as an associative array.

oci_error() Array Description
Array key Type Description
code integer The Oracle error number.
message string The Oracle error text.
offset integer The byte position of an error in the SQL statement. If there was no statement, this is 0
sqltext string The SQL statement text. If there was no statement, this is an empty string.

Examples

Example #1 Displaying the Oracle error message after a connection error

<?php
$conn 
oci_connect("hr""welcome""localhost/XE");
if (!
$conn) {
    
$e oci_error();   // For oci_connect errors do not pass a handle
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #2 Displaying the Oracle error message after a parsing error

<?php
$stid 
oci_parse($conn"select ' from dual");  // note mismatched quote
if (!$stid) {
    
$e oci_error($conn);  // For oci_parse errors pass the connection handle
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error

<?php
$stid 
oci_parse($conn"select does_not_exist from dual");
$r oci_execute($stid);
if (!
$r) {
    
$e oci_error($stid);  // For oci_execute errors pass the statement handle
    
print htmlentities($e['message']);
    print 
"\n<pre>\n";
    print 
htmlentities($e['sqltext']);
    
printf("\n%".($e['offset']+1)."s""^");
    print  
"\n</pre>\n";
}
?>



oci_execute

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_executeExecutes a statement

Description

oci_execute ( resource $statement [, int $mode = OCI_COMMIT_ON_SUCCESS ] ) : bool

Executes a statement previously returned from oci_parse().

After execution, statements like INSERT will have data committed to the database by default. For statements like SELECT, execution performs the logic of the query. Query results can subsequently be fetched in PHP with functions like oci_fetch_array().

Each parsed statement may be executed multiple times, saving the cost of re-parsing. This is commonly used for INSERT statements when data is bound with oci_bind_by_name().

Parameters

statement

A valid OCI statement identifier.

mode

An optional second parameter can be one of the following constants:
Execution Modes
Constant Description
OCI_COMMIT_ON_SUCCESS Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default.
OCI_DESCRIBE_ONLY Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail.
OCI_NO_AUTO_COMMIT Do not automatically commit changes. Prior to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT which is equivalent to OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts or continues a transaction. Transactions are automatically rolled back when the connection is closed, or when the script ends. Explicitly call oci_commit() to commit a transaction, or oci_rollback() to abort it.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

If OCI_NO_AUTO_COMMIT mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_execute() for queries

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

Example #2 oci_execute() without specifying a mode example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'INSERT INTO mytab (col1) VALUES (123)');

oci_execute($stid); // The row is committed and immediately visible to other users

?>

Example #3 oci_execute() with OCI_NO_AUTO_COMMIT example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid':bv'$i10);
for (
$i 1$i <= 5; ++$i) {
    
oci_execute($stidOCI_NO_AUTO_COMMIT);  // use OCI_DEFAULT for PHP <= 5.3.1
}
oci_commit($conn);  // commits all new values: 1, 2, 3, 4, 5

?>

Example #4 oci_execute() with different commit modes example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stidOCI_NO_AUTO_COMMIT);  // data not committed

$stid oci_parse($conn'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid);  // commits both 123 and 456 values

?>

Example #5 oci_execute() with OCI_DESCRIBE_ONLY example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'SELECT * FROM locations');
oci_execute($sOCI_DESCRIBE_ONLY);
for (
$i 1$i <= oci_num_fields($stid); ++$i) {
    echo 
oci_field_name($stid$i) . "<br>\n";
}

?>

Notes

Note:

Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note:

Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

See Also

  • oci_parse() - Prepares an Oracle statement for execution



oci_fetch_all

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_allFetches multiple rows from a query into a two-dimensional array

Description

oci_fetch_all ( resource $statement , array &$output [, int $skip = 0 [, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC ]]] ) : int

Fetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.

This function can be called only once for each query executed with oci_execute().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

output

The variable to contain the returned rows.

LOB columns are returned as strings, where Oracle supports conversion.

See oci_fetch_array() for more information on how data and types are fetched.

skip

The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

maxrows

The number of rows to return. The default is -1 meaning return all the rows from skip + 1 onwards.

flags

Parameter flags indicates the array structure and whether associative arrays should be used.
oci_fetch_all() Array Structure Modes
Constant Description
OCI_FETCHSTATEMENT_BY_ROW The outer array will contain one sub-array per query row.
OCI_FETCHSTATEMENT_BY_COLUMN The outer array will contain one sub-array per query column. This is the default.

Arrays can be indexed either by column heading or numerically. Only one index mode will be returned.
oci_fetch_all() Array Index Modes
Constant Description
OCI_NUM Numeric indexes are used for each column's array.
OCI_ASSOC Associative indexes are used for each column's array. This is the default.

Use the addition operator "+" to choose a combination of array structure and index modes.

Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on output to verify the appropriate case to use for each query.

Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.

Return Values

Returns the number of rows in output, which may be 0 or more, or FALSE on failure.

Examples

Example #1 oci_fetch_all() example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows oci_fetch_all($stid$res);

echo 
"$nrows rows fetched<br>\n";
var_dump($res);

// var_dump output is:
//    2 rows fetched
//    array(2) {
//      ["POSTAL_CODE"]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(6) "10934x"
//      }
//      ["CITY"]=>
//      array(2) {
//        [0]=>
//        string(4) "Roma"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

// Pretty-print the results
echo "<table border='1'>\n";
foreach (
$res as $col) {
    echo 
"<tr>\n";
    foreach (
$col as $item) {
        echo 
"    <td>".($item !== null htmlentities($itemENT_QUOTES) : "")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows oci_fetch_all($stid$resnullnullOCI_FETCHSTATEMENT_BY_ROW);

echo 
"$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "00989x"
//        ["CITY"]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "10934x"
//        ["CITY"]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_all() with OCI_NUM

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows oci_fetch_all($stid$resnullnullOCI_FETCHSTATEMENT_BY_ROW OCI_NUM);

echo 
"$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        [0]=>
//        string(6) "10934x"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Using skip is very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.

Note:

Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

See Also



oci_fetch_array

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_arrayReturns the next row from a query as an associative or numeric array

Description

oci_fetch_array ( resource $statement [, int $mode ] ) : array

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

If statement corresponds to a PL/SQL block returning Oracle Database 12c Implicit Result Sets, then rows from all sets are consecutively fetched. If statement is returned by oci_get_implicit_resultset(), then only the subset of rows for one child query are returned.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Can also be a statement identifier returned by oci_get_implicit_resultset().

mode

An optional second parameter can be any combination of the following constants:
oci_fetch_array() Modes
Constant Description
OCI_BOTH Returns an array with both associative and numeric indices. This is the same as OCI_ASSOC + OCI_NUM and is the default behavior.
OCI_ASSOC Returns an associative array.
OCI_NUM Returns a numeric array.
OCI_RETURN_NULLS Creates elements for NULL fields. The element values will be a PHP NULL.
OCI_RETURN_LOBS Returns the contents of LOBs instead of the LOB descriptors.

The default mode is OCI_BOTH.

Use the addition operator "+" to specify more than one mode at a time.

Return Values

Returns an array with associative and/or numeric indices. If there are no more rows in the statement then FALSE is returned.

By default, LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

The table name is not included in the array index. If your query contains two different columns with the same name, use OCI_NUM or add a column alias to the query to ensure name uniqueness, see example #7. Otherwise only one column will be returned via PHP.

Examples

Example #1 oci_fetch_array() with OCI_BOTH

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_BOTH)) != false) {
    
// Use the uppercase column names for the associative array indices
    
echo $row[0] . " and " $row['DEPARTMENT_ID']   . " are the same<br>\n";
    echo 
$row[1] . " and " $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_array() with OCI_NUM

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, description FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_NUM)) != false) {
    echo 
$row[0] . "<br>\n";
    echo 
$row[1]->read(11) . "<br>\n"// this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_array() with OCI_ASSOC

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, description FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_ASSOC)) != false) {
    echo 
$row['ID'] . "<br>\n";
    echo 
$row['DESCRIPTION']->read(11) . "<br>\n"// this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_fetch_array() with OCI_RETURN_NULLS

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT 1, null FROM dual');
oci_execute($stid);
while ((
$row oci_fetch_array ($stidOCI_ASSOC)) != false) { // Ignore NULLs
    
var_dump($row);
}

/*
The above code prints:
  array(1) {
    [1]=>
    string(1) "1"
  }
*/

$stid oci_parse($conn'SELECT 1, null FROM dual');
oci_execute($stid);
while ((
$row oci_fetch_array ($stidOCI_ASSOC+OCI_RETURN_NULLS)) != false) { // Fetch NULLs
    
var_dump($row);
}

/*
The above code prints:
  array(2) {
    [1]=>
    string(1) "1"
    ["NULL"]=>
    NULL
  }
*/

?>

Example #5 oci_fetch_array() with OCI_RETURN_LOBS

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, description FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_LOBS)) != false) {
    echo 
$row['ID'] . "<br>\n";
    echo 
$row['DESCRIPTION'] . "<br>\n"// this contains all of DESCRIPTION
    // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
    
unset($row); 
}

// Output is:
//    1
//    A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 oci_fetch_array() with case sensitive column names

<?php

/*
   Before running, create the table:
      CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
      INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
      COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'select * from mytab');
oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS);

// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index.  However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n";   //  prints Chris
print $row['CITY'] . "<br>\n";   //  prints Melbourne

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 oci_fetch_array() with columns having duplicate names

<?php

/*
  Before running, create the tables:
      CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycity (id, name) values (1, 'Melbourne');
      CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycountry (id, name) values (1, 'Australia');
      COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'SELECT mycity.name, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id'
;
$stid oci_parse($conn$sql);
oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC);
var_dump($row);

// Output only contains one "NAME" entry:
//    array(1) {
//      ["NAME"]=>
//      string(9) "Australia"
//    }

// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql 'SELECT mycity.name AS ctnm, mycountry.name 
        FROM mycity, mycountry 
        WHERE mycity.id = mycountry.id'
;
$stid oci_parse($conn$sql);
oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC);
var_dump($row);

// Output now contains both columns selected:
//    array(2) {
//      ["CTNM"]=>
//      string(9) "Melbourne"
//      ["NAME"]=>
//      string(9) "Australia"
//    }


oci_free_statement($stid);
oci_close($conn);

?>

Example #8 oci_fetch_array() with DATE columns

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid oci_parse($conn"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);

$stid oci_parse($conn'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row oci_fetch_array($stidOCI_ASSOC);
echo 
$row['HIRE_DATE'] . "<br>\n";  // prints 1997-06-14

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 oci_fetch_array() with REF CURSOR

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'BEGIN myproc(:rc); END;');
$refcur oci_new_cursor($conn);
oci_bind_by_name($stid':rc'$refcur, -1OCI_B_CURSOR);
oci_execute($stid);

// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);  
echo 
"<table border='1'>\n";
while ((
$row oci_fetch_array($refcurOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>".($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Pagination with oci_fetch_array() using a LIMIT-like query

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Find the version of the database
preg_match('/Release ([0-9]+)\./'oci_server_version($conn), $matches);
$oracleversion $matches[1];

// This is the query you want to "page" through
$sql 'SELECT city, postal_code FROM locations ORDER BY city';

if (
$oracleversion >= 12) {
    
// Make use of Oracle 12c OFFSET / FETCH NEXT syntax
    
$sql $sql ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
    
// Older Oracle versions need a nested query selecting a subset
    // from $sql.  Or, if the SQL statement is known at development
    // time, consider using a row_number() function instead of this
    // nested solution.  In production environments, be careful to
    // avoid SQL Injection issues with concatenation.
    
$sql "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
                           FROM (
$sql) a
                           WHERE ROWNUM <= :offset + :numrows)
            WHERE my_rnum > :offset"
;
}

$offset  0;  // skip this many rows
$numrows 5;  // return 5 rows
$stid oci_parse($conn$sql);
oci_bind_by_name($stid':numrows'$numrows);
oci_bind_by_name($stid':offset'$offset);
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_ASSOC OCI_RETURN_NULLS)) != false) {
    echo 
$row['CITY'] . " " $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    Geneva 1730
//    Hiroshima 6823

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 oci_fetch_array() with Oracle Database 12c Implicit Result Sets

<?php

$conn 
oci_connect('hr''welcome''localhost/pdborcl');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Requires OCI8 2.0 and Oracle Database 12c
// Also see oci_get_implicit_resultset()
$sql 'DECLARE
           c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;'
;

$stid oci_parse($conn$sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while ((
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"  <td>".($item!==null?htmlentities($itemENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

// Output is:
//    Beijing 190518
//    Bern    3095
//    Bombay  490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Note:

The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

See Also



oci_fetch_assoc

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_assocReturns the next row from a query as an associative array

Description

oci_fetch_assoc ( resource $statement ) : array

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an associative array. If there are no more rows in the statement then FALSE is returned.

Examples

Example #1 oci_fetch_assoc() Example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while ((
$row oci_fetch_assoc($stid)) != false) {
    echo 
$row['DEPARTMENT_ID'] . " " $row['DEPARTMENT_NAME'] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

See oci_fetch_array() for more examples of fetching rows.

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array



oci_fetch_object

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_objectReturns the next row from a query as an object

Description

oci_fetch_object ( resource $statement ) : object

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the statement then FALSE is returned.

Any LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case for attribute access.

Attribute values will be NULL for any NULL data fields.

Examples

Example #1 oci_fetch_object() example

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
    INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, description FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_object($stid)) != false) {
    
// Use upper case attribute names for each standard Oracle column
    
echo $row->ID "<br>\n";
    echo 
$row->DESCRIPTION "<br>\n"
}

// Output is:
//    1
//    Fish and Chips

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_object() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_object($stid)) != false) {
    
// Use upper case attribute names for each standard Oracle column
    
echo $row->ID "<br>\n";
    
// Use the exact case for the case sensitive column name
    
echo $row->MyDescription "<br>\n";   
}

// Output is:
//    1
//    Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_object() with LOBs

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description CLOB);
    INSERT INTO mytab (id, description) values (1, 'A very long string');
    COMMIT;
*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT id, description FROM mytab');
oci_execute($stid);

while ((
$row oci_fetch_object($stid)) != false) {
    echo 
$row->ID "<br>\n";
    
// The following will output the first 11 bytes from DESCRIPTION
    
echo $row->DESCRIPTION->read(11) . "<br>\n"
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

See Also

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_row() - Returns the next row from a query as a numeric array



oci_fetch_row

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_rowReturns the next row from a query as a numeric array

Description

oci_fetch_row ( resource $statement ) : array

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM + OCI_RETURN_NULLS.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns a numerically indexed array. If there are no more rows in the statement then FALSE is returned.

Examples

Example #1 oci_fetch_row() Example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while ((
$row oci_fetch_row($stid)) != false) {
    echo 
$row[0] . " " $row[1] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

See oci_fetch_array() for more examples of fetching rows.

See Also



oci_fetch

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetchFetches the next row from a query into internal buffers

Description

oci_fetch ( resource $statement ) : bool

Fetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().

See oci_fetch_array() for general information about fetching data.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Return Values

Returns TRUE on success or FALSE if there are no more rows in the statement.

Examples

Example #1 oci_fetch() with defined variables

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid oci_parse($conn$sql);

// The defines MUST be done before executing
oci_define_by_name($stid'LOCATION_ID'$locid);
oci_define_by_name($stid'CITY'$city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo 
"Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch() with oci_result()

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid oci_parse($conn$sql);
oci_execute($stid);

while (
oci_fetch($stid)) {
    echo 
oci_result($stid'LOCATION_ID') . " is ";
    echo 
oci_result($stid'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.

See Also



oci_field_is_null

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_is_nullChecks if a field in the currently fetched row is NULL

Description

oci_field_is_null ( resource $statement , mixed $field ) : bool

Checks if the given field from the current row of statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns TRUE if field is NULL, FALSE otherwise.

Examples

Example #1 oci_field_name() example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER);
//   INSERT INTO mytab VALUES (1);
//   INSERT INTO mytab VALUES (NULL);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stid);

while ((
$row oci_fetch_array($stidOCI_RETURN_NULLS)) != false) {
    
$ncols oci_num_fields($stid);
    for (
$col 1$col <= $ncols$col++) {
        
var_dump(oci_field_is_null($stid$col));
    }    
}

// Outputs:
//    bool(false)
//    bool(true)

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.



oci_field_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_nameReturns the name of a field from the statement

Description

oci_field_name ( resource $statement , mixed $field ) : string

Returns the name of the field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the name as a string, or FALSE on errors.

Examples

Example #1 oci_field_name() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
//                       clob_col CLOB, date_col DATE);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo 
"<tr>";
echo 
"<th>Name</th>";
echo 
"<th>Type</th>";
echo 
"<th>Length</th>";
echo 
"</tr>\n";

$ncols oci_num_fields($stid);

for (
$i 1$i <= $ncols$i++) {
    
$column_name  oci_field_name($stid$i);
    
$column_type  oci_field_type($stid$i);

    echo 
"<tr>";
    echo 
"<td>$column_name</td>";
    echo 
"<td>$column_type</td>";
    echo 
"</tr>\n";
}

echo 
"</table>\n";

// Outputs:
//    Name           Type
//    NUMBER_COL    NUMBER
//    VARCHAR2_COL  VARCHAR2
//    CLOB_COL      CLOB
//    DATE_COL      DATE

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_field_precision

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_precisionTell the precision of a field

Description

oci_field_precision ( resource $statement , mixed $field ) : int

Returns precision of the field.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the precision as an integer, or FALSE on errors.

Examples

Example #1 oci_field_precision() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols oci_num_fields($stid);
for (
$i 1$i <= $ncols$i++) {
    echo 
oci_field_name($stid$i) . " " 
        
oci_field_precision($stid$i) . " " 
        
oci_field_scale($stid$i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_field_scale

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_scaleTell the scale of the field

Description

oci_field_scale ( resource $statement , mixed $field ) : int

Returns the scale of the column with field index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the scale as an integer, or FALSE on errors.

Examples

Example #1 oci_field_scale() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols oci_num_fields($stid);
for (
$i 1$i <= $ncols$i++) {
    echo 
oci_field_name($stid$i) . " " 
        
oci_field_precision($stid$i) . " " 
        
oci_field_scale($stid$i) . "<br>\n";
}

// Outputs:
//   C1    0 -127
//   C2  126 -127
//   C3    4    0
//   C4    5    3

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_field_size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_sizeReturns field's size

Description

oci_field_size ( resource $statement , mixed $field ) : int

Returns the size of a field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the size of a field in bytes, or FALSE on errors.

Examples

Example #1 oci_field_size() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), 
//                       clob_col CLOB, date_col DATE);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo 
"<tr>";
echo 
"<th>Name</th>";
echo 
"<th>Type</th>";
echo 
"<th>Length</th>";
echo 
"</tr>\n";

$ncols oci_num_fields($stid);

for (
$i 1$i <= $ncols$i++) {
    
$column_name  oci_field_name($stid$i);
    
$column_type  oci_field_type($stid$i);
    
$column_size  oci_field_size($stid$i);

    echo 
"<tr>";
    echo 
"<td>$column_name</td>";
    echo 
"<td>$column_type</td>";
    echo 
"<td>$column_size</td>";
    echo 
"</tr>\n";
}

echo 
"</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_field_type_raw

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_type_rawTell the raw Oracle data type of the field

Description

oci_field_type_raw ( resource $statement , mixed $field ) : int

Returns Oracle's raw "SQLT" data type of the field.

If you want a field's type name, then use oci_field_type() instead.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns Oracle's raw data type as a number, or FALSE on errors.

Examples

Example #1 oci_field_type_raw() Example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn'select * from mytab');
oci_execute($stidOCI_DESCRIBE_ONLY);  // Use OCI_DESCRIBE_ONLY if not fetching rows
$n oci_num_fields($stid);
for (
$i 1$i <= $n; ++$i) {
    echo 
oci_field_name($stid$i) . " is raw type: " oci_field_type_raw($stid$i) . "<br>\n";
}

// Output is:
//    NUMBER_COL is raw type: 2
//    VARCHAR2_COL is raw type: 1
//    CLOB_COL is raw type: 112
//    DATE_COL is raw type: 12

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.



oci_field_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_typeReturns a field's data type name

Description

oci_field_type ( resource $statement , mixed $field ) : mixed

Returns a field's data type name.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the field data type as a string, or FALSE on errors.

Examples

Example #1 oci_field_type() example

<?php

// Create the table with:
//   CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), 
//                       clob_col CLOB, date_col DATE);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo 
"<tr>";
echo 
"<th>Name</th>";
echo 
"<th>Type</th>";
echo 
"<th>Length</th>";
echo 
"</tr>\n";

$ncols oci_num_fields($stid);

for (
$i 1$i <= $ncols$i++) {
    
$column_name  oci_field_name($stid$i);
    
$column_type  oci_field_type($stid$i);
    
$column_size  oci_field_size($stid$i);

    echo 
"<tr>";
    echo 
"<td>$column_name</td>";
    echo 
"<td>$column_type</td>";
    echo 
"<td>$column_size</td>";
    echo 
"</tr>\n";
}

echo 
"</table>\n";

// Outputs:
//    Name           Type       Length
//    NUMBER_COL    NUMBER        22
//    VARCHAR2_COL  VARCHAR2       1
//    CLOB_COL      CLOB        4000
//    DATE_COL      DATE           7

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_free_descriptor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_free_descriptorFrees a descriptor

Description

oci_free_descriptor ( resource $descriptor ) : bool

Frees a descriptor allocated by oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function is commonly used as a method OCI-LOB::free.

See Also



oci_free_statement

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_free_statementFrees all resources associated with statement or cursor

Description

oci_free_statement ( resource $statement ) : bool

Frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns TRUE on success or FALSE on failure.



oci_get_implicit_resultset

(PHP 5 >= 5.6.0, PHP 7, PECL OCI8 >= 2.0.0)

oci_get_implicit_resultsetReturns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

Description

oci_get_implicit_resultset ( resource $statement ) : resource

Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with Oracle's DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.

The child statement can be used with any of the OCI8 fetching functions: oci_fetch(), oci_fetch_all(), oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() or oci_fetch_row()

Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.

Return Values

Returns a statement handle for the next child statement available on statement. Returns FALSE when child statements do not exist, or all child statements have been returned by previous calls to oci_get_implicit_resultset().

Examples

Example #1 Fetching Implicit Result Sets in a loop

<?php

$conn 
oci_connect('hr''welcome''localhost/pdborcl');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;'
;

$stid oci_parse($conn$sql);
oci_execute($stid);

while ((
$stid_c oci_get_implicit_resultset($stid))) {
    echo 
"<h2>New Implicit Result Set:</h2>\n";
    echo 
"<table>\n";
    while ((
$row oci_fetch_array($stid_cOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
        echo 
"<tr>\n";
        foreach (
$row as $item) {
            echo 
"  <td>".($item!==null?htmlentities($itemENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
        }
        echo 
"</tr>\n";
    }
    echo 
"</table>\n";
}

// Output is:
//    New Implicit Result Set:
//     Beijing 190518
//     Bern    3095
//     Bombay  490231
//    New Implicit Result Set:
//     CN
//     CH
//     IN

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Getting child statement handles individually

<?php

$conn 
oci_connect('hr''welcome''localhost/pdborcl');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;'
;

$stid oci_parse($conn$sql);
oci_execute($stid);

$stid_1 oci_get_implicit_resultset($stid);
$stid_2 oci_get_implicit_resultset($stid);

$row oci_fetch_array($stid_1OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row oci_fetch_array($stid_2OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row oci_fetch_array($stid_1OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row oci_fetch_array($stid_2OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);

// Output is:
//    array(2) {
//      ["CITY"]=>
//      string(7) "Beijing"
//      ["POSTAL_CODE"]=>
//      string(6) "190518"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CN"
//    }
//    array(2) {
//      ["CITY"]=>
//      string(4) "Bern"
//      ["POSTAL_CODE"]=>
//      string(4) "3095"
//    }
//    array(1) {
//      ["COUNTRY_ID"]=>
//      string(2) "CH"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Explicitly setting the Prefetch Count

<?php

$conn 
oci_connect('hr''welcome''localhost/pdborcl');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;'
;

$stid oci_parse($conn$sql);
oci_execute($stid);

$stid_c oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c200);   // Set the prefetch before fetching from the child statement
echo "<table>\n";
while ((
$row oci_fetch_array($stid_cOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"  <td>".($item!==null?htmlentities($itemENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Implicit Result Set example without using oci_get_implicit_resultset()

All results from all queries are returned consecutively.

<?php

$conn 
oci_connect('hr''welcome''localhost/pdborcl');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'DECLARE
            c1 SYS_REFCURSOR;
        BEGIN
           OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
           OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
           DBMS_SQL.RETURN_RESULT(c1);
        END;'
;

$stid oci_parse($conn$sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while ((
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"  <td>".($item!==null?htmlentities($itemENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

// Output is:
//    Beijing 190518
//    Bern 3095
//    Bombay 490231
//    CN
//    CH
//    IN

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().



oci_internal_debug

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_internal_debugEnables or disables internal debug output

Description

oci_internal_debug ( bool $onoff ) : void

Enables or disables internal debug output.

Parameters

onoff

Set this to FALSE to turn debug output off or TRUE to turn it on.

Return Values

No value is returned.

Notes

Note:

In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.



oci_lob_copy

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_copyCopies large object

Description

oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0 ] ) : bool

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use OCI-Lob::seek() to move LOB internal pointers.

Parameters

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Return Values

Returns TRUE on success or FALSE on failure.



oci_lob_is_equal

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_is_equalCompares two LOB/FILE locators for equality

Description

oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $lob2 ) : bool

Compares two LOB/FILE locators.

Parameters

lob1

A LOB identifier.

lob2

A LOB identifier.

Return Values

Returns TRUE if these objects are equal, FALSE otherwise.



oci_new_collection

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_collectionAllocates new collection object

Description

oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] ) : OCI-Collection

Allocates a new collection object.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

tdo

Should be a valid named type (uppercase).

schema

Should point to the scheme, where the named type was created. The name of the current user is the default value.

Return Values

Returns a new OCICollection object or FALSE on error.

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.



oci_new_connect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_connectConnect to the Oracle server using a unique connection

Description

oci_new_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] ) : resource

Establishes a new connection to an Oracle server and logs on.

Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.

Parameters

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

The following demonstrates how you can separate connections.

Example #1 oci_new_connect() example

<?php

// create table mytab (mycol number);

function query($name$c)
{
    echo 
"Querying $name\n";
    
$s oci_parse($c"select * from mytab");
    
oci_execute($sOCI_NO_AUTO_COMMIT);
    
$row oci_fetch_array($sOCI_ASSOC);
    if (!
$row) {
        echo 
"No rows\n";
    } else {
        do {
            foreach (
$row as $item)
                echo 
$item " ";
            echo 
"\n";
        } while ((
$row oci_fetch_array($sOCI_ASSOC)) != false);
    }
}

$c1 oci_connect("hr""welcome""localhost/orcl");
$c2 oci_new_connect("hr""welcome""localhost/orcl");

$s oci_parse($c1"insert into mytab values(1234)");
oci_execute($sOCI_NO_AUTO_COMMIT);

query("basic connection"$c1);
query("new connection"$c2);
oci_commit($c1);
query("new connection after commit"$c2);

// Output is:
//   Querying basic connection
//   1234 
//   Querying new connection
//   No rows
//   Querying new connection after commit
//   1234 

?>

See oci_connect() for further examples of parameter usage.

See Also



oci_new_cursor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_cursorAllocates and returns a new cursor (statement handle)

Description

oci_new_cursor ( resource $connection ) : resource

Allocates a new statement handle on the specified connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Return Values

Returns a new statement handle, or FALSE on error.

Examples

Example #1 Binding a REF CURSOR in an Oracle stored procedure call

<?php

// Precreate:
//   create or replace procedure myproc(myrc out sys_refcursor) as
//   begin
//     open myrc for select first_name from employees;
//   end;

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$curs oci_new_cursor($conn);
$stid oci_parse($conn"begin myproc(:cursbv); end;");
oci_bind_by_name($stid":cursbv"$curs, -1OCI_B_CURSOR);
oci_execute($stid);

oci_execute($curs);  // Execute the REF CURSOR like a normal statement id
while (($row oci_fetch_array($cursOCI_ASSOC+OCI_RETURN_NULLS)) != false) {
    echo 
$row['FIRST_NAME'] . "<br />\n";
}

oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.



oci_new_descriptor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_descriptorInitializes a new empty LOB or FILE descriptor

Description

oci_new_descriptor ( resource $connection [, int $type = OCI_DTYPE_LOB ] ) : OCI-Lob

Allocates resources to hold descriptor or LOB locator.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

type

Valid values for type are: OCI_DTYPE_FILE, OCI_DTYPE_LOB and OCI_DTYPE_ROWID.

Return Values

Returns a new LOB or FILE descriptor on success, FALSE on error.

Examples

Example #1 oci_new_descriptor() example

<?php
/* This script is designed to be called from a HTML form.
 * It expects $user, $password, $table, $where, and $commitsize
 * to be passed in from the form.  The script then deletes
 * the selected rows using the ROWID and commits after each
 * set of $commitsize rows. (Use with care, there is no rollback)
 */
$conn oci_connect($user$password);
$stmt oci_parse($conn"select rowid from $table $where");
$rowid oci_new_descriptor($connOCI_D_ROWID);
oci_define_by_name($stmt"ROWID"$rowid);
oci_execute($stmt);
while (
oci_fetch($stmt)) {
    
$nrows oci_num_rows($stmt);
    
$delete oci_parse($conn"delete from $table where ROWID = :rid");
    
oci_bind_by_name($delete":rid"$rowid, -1OCI_B_ROWID);
    
oci_execute($delete);
    echo 
"$nrows\n";
    if ((
$nrows $commitsize) == 0) {
        
oci_commit($conn);
    }
}
$nrows oci_num_rows($stmt);
echo 
"$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>
<?php
    
/* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload" />
     * ...
     */
  
if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
  
} else {

     
// $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     
$conn oci_connect($user$password);
     
$lob oci_new_descriptor($connOCI_D_LOB);
     
$stmt oci_parse($conn"insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob"
);
     
oci_bind_by_name($stmt':the_blob'$lob, -1OCI_B_BLOB);
     
oci_execute($stmtOCI_DEFAULT);
     if (
$lob->savefile($lob_upload)){
        
oci_commit($conn);
        echo 
"Blob successfully uploaded\n";
     }else{
        echo 
"Couldn't upload Blob\n";
     }
     
$lob->free();
     
oci_free_statement($stmt);
     
oci_close($conn);
  }
?>

Example #2 oci_new_descriptor() example

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters.
 * Example PL/SQL stored procedure signature is:
 *
 * PROCEDURE save_data
 *   Argument Name                  Type                    In/Out Default?
 *   ------------------------------ ----------------------- ------ --------
 *   KEY                            NUMBER(38)              IN
 *   DATA                           CLOB                    IN
 *
 */

$conn oci_connect($user$password);
$stmt oci_parse($conn"begin save_data(:key, :data); end;");
$clob oci_new_descriptor($connOCI_D_LOB);
oci_bind_by_name($stmt':key'$key);
oci_bind_by_name($stmt':data'$clob, -1OCI_B_CLOB);
$clob->write($data);
oci_execute($stmtOCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_num_fields

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_num_fieldsReturns the number of result columns in a statement

Description

oci_num_fields ( resource $statement ) : int

Gets the number of columns in the given statement.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of columns as an integer, or FALSE on errors.

Examples

Example #1 oci_num_fields() example

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, quantity NUMBER);

$conn oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"SELECT * FROM mytab");
oci_execute($stidOCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols oci_num_fields($stid);
for (
$i 1$i <= $ncols$i++) {
    echo 
oci_field_name($stid$i) . " " oci_field_type($stid$i) . "<br>\n";
}

// Outputs:
//    ID NUMBER
//    QUANTITY NUMBER

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.



oci_num_rows

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_num_rowsReturns number of rows affected during statement execution

Description

oci_num_rows ( resource $statement ) : int

Gets the number of rows affected during statement execution.

Parameters

statement

A valid OCI statement identifier.

Return Values

Returns the number of rows affected as an integer, or FALSE on errors.

Examples

Example #1 oci_num_rows() example

<?php

$conn 
oci_connect("hr""hrpwd""localhost/XE");
if (!
$conn) {
    
$m oci_error();
    
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid oci_parse($conn"create table emp2 as select * from employees");
oci_execute($stid);
echo 
oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);

$stid oci_parse($conn"delete from emp2");
oci_execute($stidOCI_DEFAULT);
echo 
oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);

$stid oci_parse($conn"drop table emp2");
oci_execute($stid);
oci_free_statement($stid);

oci_close($conn);

?>

Notes

Note:

This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.

Note:

In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.



oci_parse

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_parsePrepares an Oracle statement for execution

Description

oci_parse ( resource $connection , string $sql_text ) : resource

Prepares sql_text using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Statement identifiers can be freed with oci_free_statement() or by setting the variable to NULL.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

sql_text

The SQL or PL/SQL statement.

SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").

Return Values

Returns a statement handle on success, or FALSE on error.

Examples

Example #1 oci_parse() example for SQL statements

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');

// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

Example #2 oci_parse() example for PL/SQL statements

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 8;

// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid oci_parse($conn'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid':p1'$p1);
oci_bind_by_name($stid':p2'$p240);

oci_execute($stid);

print 
"$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

This function does not validate sql_text. The only way to find out if sql_text is a valid SQL or PL/SQL statement is to execute it.

See Also



oci_password_change

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_password_changeChanges password of Oracle's user

Description

oci_password_change ( resource $connection , string $username , string $old_password , string $new_password ) : bool
oci_password_change ( string $dbname , string $username , string $old_password , string $new_password ) : resource

Changes password for user with username.

The oci_password_change() function is most useful for PHP command-line scripts, or when non-persistent connections are used throughout the PHP application.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

username

The Oracle user name.

old_password

The old password.

new_password

The new password to be set.

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_password_change() example changing the password of an already connected user

<?php

$dbase      
'localhost/orcl';
$user       'cj';
$current_pw 'welcome';
$new_pw     'geelong';

$c oci_pconnect($user$current_pw$dbase);
oci_password_change($c$user$current_pw$new_pw);
echo 
"New password is : " $new_pw "\n";

?>

Example #2 oci_password_change() example of connecting and changing the password in one step

<?php

$dbase      
'localhost/orcl';
$user       'cj';
$current_pw 'welcome';
$new_pw     'geelong';

$c oci_pconnect($user$current_pw$dbase);
if (!
$c) {
    
$m oci_error();
    if (
$m['code'] == 28001) { // "ORA-28001: the password has expired"
        // Login and reset password at the same time
        
$c oci_password_change($dbase$user$current_pw$new_pw);
        if (
$c) {
            echo 
"New password is : " $new_pw "\n";
        }
    }
}

if (!
$c) {  // The original error wasn't 28001, or the password change failed
    
$m oci_error();
    
trigger_error('Could not connect to database: '$m['message'], E_USER_ERROR);
}

// Use the connection $c
...

?>

Notes

Note:

Changing the password either with this function or directly in Oracle should be done carefully. This is because PHP applications may continue to successfully reuse persistent connections by authenticating with the old password. The best practice is to restart all web servers whenever the user password is changed.

Note:

If upgrading the Oracle client libraries or the database from a release prior to 11.2.0.3 to version 11.2.0.3 or higher, oci_password_change() may give the error "ORA-1017: invalid username/password" unless both client and server versions are upgraded at the same time.

Note:

The second oci_password_change() syntax is available since OCI8 version 1.1.

Note:

In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.



oci_pconnect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_pconnectConnect to an Oracle database using a persistent connection

Description

oci_pconnect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] ) : resource

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.

Parameters

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Return Values

Returns a connection identifier or FALSE on error.

Examples

Example #1 Basic oci_pconnect() Example using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn oci_pconnect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid oci_parse($conn'SELECT * FROM employees');
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>" . ($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

?>

See oci_connect() for further examples of parameter usage.

Notes

Note: Starting with PHP 5.1.2 and PECL OCI8 1.1, the lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

See Also



oci_register_taf_callback

(PHP 7.0 >= 7.0.21, PHP 7 >= 7.1.7, PECL OCI8 >= 2.1.7)

oci_register_taf_callbackRegister a user-defined callback function for Oracle Database TAF

Description

oci_register_taf_callback ( resource $connection [, mixed $callbackFn ] ) : bool

Registers a user-defined callback function to connection. If connection fails due to instance or network failure, the registered callback function will be invoked for several times during failover. See OCI8 Transparent Application Failover (TAF) Support for information.

When oci_register_taf_callback() is called multiple times, each registration overwrites the previous one.

Use oci_unregister_taf_callback() to explicitly unregister a user-defined callback.

TAF callback registration will NOT be saved across persistent connections, therefore the callback needs to be re-registered for a new persistent connection.

Parameters

connection

An Oracle connection identifier.

callbackFn

A user-defined callback to register for Oracle TAF. It can be a string of the function name or a Closure (anonymous function).

The interface of a TAF user-defined callback function is as follows:

userCallbackFn ( resource $connection , int $event , int $type ) : int

See the parameter description and an example on OCI8 Transparent Application Failover (TAF) Support page.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



oci_result

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_resultReturns field's value from the fetched row

Description

oci_result ( resource $statement , mixed $field ) : mixed

Returns the data from field in the current row, fetched by oci_fetch().

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parameters

statement

field

Can be either use the column number (1-based) or the column name. The case of the column name must be the case that Oracle meta data describes the column as, which is uppercase for columns created case insensitively.

Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Examples

Example #1 oci_fetch() with oci_result()

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
if (!
$conn) {
    
$e oci_error();
    
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid oci_parse($conn$sql);
oci_execute($stid);

while (
oci_fetch($stid)) {
    echo 
oci_result($stid'LOCATION_ID') . " is ";
    echo 
oci_result($stid'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

See Also



oci_rollback

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_rollbackRolls back the outstanding database transaction

Description

oci_rollback ( resource $connection ) : bool

Reverts all uncommitted changes for the Oracle connection and ends the transaction. It releases all locks held. All Oracle SAVEPOINTS are erased.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 oci_rollback() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn"INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r oci_execute($stidOCI_NO_AUTO_COMMIT);
if (!
$r) {    
    
$e oci_error($stid);
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid oci_parse($conn'INSERT INTO myschedule (startday) VALUES (12)');
$r oci_execute($stidOCI_NO_AUTO_COMMIT);
if (!
$r) {    
    
$e oci_error($stid);
    
oci_rollback($conn);  // rollback changes to both tables
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r oci_commit($conn);
if (!
r) {
    
$e oci_error($conn);
    
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Example #2 Rolling back to a SAVEPOINT example

<?php
$stid 
oci_parse($conn'UPDATE mytab SET id = 1111');
oci_execute($stidOCI_NO_AUTO_COMMIT);

// Create the savepoint
$stid oci_parse($conn'SAVEPOINT mysavepoint');
oci_execute($stidOCI_NO_AUTO_COMMIT);

$stid oci_parse($conn'UPDATE mytab SET id = 2222');
oci_execute($stidOCI_NO_AUTO_COMMIT);

// Use an explicit SQL statement to rollback to the savepoint
$stid oci_parse($conn'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stidOCI_NO_AUTO_COMMIT);

oci_commit($conn);  // mytab now has id of 1111
?>

Notes

Note:

Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

See Also



oci_server_version

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_server_versionReturns the Oracle Database version

Description

oci_server_version ( resource $connection ) : string

Returns a string with the Oracle Database version and available options

Parameters

connection

Return Values

Returns the version information as a string or FALSE on error.

Examples

Example #1 oci_server_version() example

<?php

$conn 
oci_connect("hr""hrpwd""localhost/XE");
echo 
"Server Version: " oci_server_version($conn);

// Displays:
// Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
// With the Partitioning, OLAP, Data Mining and Real Application Testing option

oci_close($conn);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ociserverversion() instead. This old name still can be used. However it is deprecated and not recommended.

See Also



oci_set_action

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_actionSets the action name

Description

oci_set_action ( resource $connection , string $action_name ) : bool

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The action name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

action_name

User chosen string up to 32 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the action

<?php

$c 
oci_connect('hr''welcome''localhost/XE');

// Record the action
oci_set_action($c'Friend Lookup');

// Code that causes a round-trip, for example a query:
$s oci_parse($c'select * from dual');
oci_execute($s);
oci_fetch_all($s$res);

sleep(30);

?>
   // While the script is running, the administrator can see the actions
   // being performed:
   
   sqlplus system/welcome
   SQL> select action from v$session;
   

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

See Also



oci_set_call_timeout

(PHP 7.2 >= 7.2.14, PHP 7 >= 7.3.1, PECL OCI8 >= 2.2.0)

oci_set_call_timeoutSets a millisecond timeout for database calls

Description

oci_set_call_timeout ( resource $connection , int $time_out ) : bool

Sets a timeout limiting the maxium time a database round-trip using this connection may take.

Each OCI8 operation may make zero or more calls to Oracle's client library. These internal calls may then may make zero or more round-trips to Oracle Database. If any one of those round-trips takes more than time_out milliseconds, then the operation is cancelled and an error is returned to the application.

The time_out value applies to each round-trip individually, not to the sum of all round-trips. Time spent processing in PHP OCI8 before or after the completion of each round-trip is not counted.

When a call is interrupted, Oracle will attempt to clean up the connection for reuse. This operation is allowed to run for another time_out period. Depending on the outcome of the cleanup, the connection may or may not be reusable.

When persistent connections are used, the timeout value will be retained across PHP requests.

The oci_set_call_timeout() function is available when OCI8 uses Oracle 18 (or later) Client libraries.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

time_out

The maximum time in milliseconds that any single round-trip between PHP and Oracle Database may take.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the timeout

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');
oci_set_call_timeout($conn5000);

?>



oci_set_client_identifier

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_client_identifierSets the client identifier

Description

oci_set_client_identifier ( resource $connection , string $client_identifier ) : bool

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The identifier can subsequently be queried, for example with SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') FROM DUAL. Database administration views such as V$SESSION will also contain the value. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing and can also be used for auditing.

The value may be retained across page requests that use the same persistent connection.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_identifier

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client identifier to the application user

<?php

// Find the application user's login name
session_start();
$un my_validate_session($_SESSION['username']);
$c oci_connect('myschema''welcome''localhost/XE');

// Tell Oracle who that user is
oci_set_client_identifier($c$un);

// The next round-trip to the database will piggyback the identifier
$s oci_parse($c'select mydata from mytable');
oci_execute($s);

// ...

?>

Notes

Caution

Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

See Also



oci_set_client_info

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_client_infoSets the client information

Description

oci_set_client_info ( resource $connection , string $client_info ) : bool

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The client information can subsequently be queried from database administration views such as V$SESSION.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_info

User chosen string up to 64 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the client information

<?php

$c 
oci_connect('hr''welcome''localhost/XE');

// Record the client information
oci_set_client_info($c'My Application Version 2');

// Code that causes a round-trip, for example a query:
$s oci_parse($c'select * from dual');
oci_execute($s);
oci_fetch_all($s$res);

sleep(30);

?>
   // While the script is running, the administrator can see the client
   // information:
   
   sqlplus system/welcome
   SQL> select client_info from v$session;
   

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

See Also



oci_set_db_operation

(PHP 7 >= 7.2.14, PHP 7 >= 7.3.1, PECL OCI8 >= 2.2.0)

oci_set_db_operationSets the database operation

Description

oci_set_db_operation ( resource $connection , string $dbop ) : bool

Sets the DBOP for Oracle tracing.

The database operation name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when a SQL statement is executed.

The database operation can subsequently be queried from database administration views such as V$SQL_MONITOR.

The oci_set_db_operation() function is available when OCI8 uses Oracle 12 (or later) Client libraries and Oracle Database 12 (or later).

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

dbop

User chosen string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting the DBOP

<?php

$c 
oci_connect('hr''welcome''localhost/XE');

// Record the operation
oci_set_db_operation($c'main query');

// Code that causes a round-trip, for example a query:
$s oci_parse($c'select * from dual');
oci_execute($s);
oci_fetch_all($s$res);

sleep(30);

?>
   // While the script is running, the administrator can see the database operations
   // being performed:
   
   sqlplus system/welcome
   SQL> select dbop_name from v$sql_monitor;
   

Notes

Caution

Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

See Also



oci_set_edition

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_editionSets the database edition

Description

oci_set_edition ( string $edition ) : bool

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling oci_connect(), oci_pconnect() or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

Parameters

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

Notes

Note: Oracle version requirement

This function is available from Oracle 11gR2 onwards.

Caution

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Caution

DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Two scripts can use different versions of myfunc() at the same time

<?php

// File 1

echo "Version 1 of application\n";

oci_set_edition('ORA$BASE');
$c oci_connect('hr''welcome''localhost/XE');

$s oci_parse($c"begin :r := myfunc(); end;");
oci_bind_by_name($s":r"$r20);
oci_execute($s);
echo 
"The result is $r\n";

?>
<?php

// File 2

echo "Version 2 of application\n";

oci_set_edition('E1');
$c oci_connect('hr''welcome''localhost/XE');

$s oci_parse($c"begin :r := myfunc(); end;");
oci_bind_by_name($s":r"$r20);
oci_execute($s);
echo 
"The result is $r\n";

?>



oci_set_module_name

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_module_nameSets the module name

Description

oci_set_module_name ( resource $connection , string $module_name ) : bool

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parameters

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

module_name

User chosen string up to 48 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Tip

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Caution

Round-trip Gotcha

Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.

Examples

Example #1 Setting the module name

<?php

$c 
oci_connect('hr''welcome''localhost/XE');

// Record the module
oci_set_module_name($c'Home Page');

// Code that causes a round-trip, for example a query:
$s oci_parse($c'select * from dual');
oci_execute($s);
oci_fetch_all($s$res);

sleep(30);
?>
   // While the script is running, the administrator can see the
   // modules in use:
   
   sqlplus system/welcome
   SQL> select module from v$session;
   

See Also



oci_set_prefetch

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_set_prefetchSets number of rows to be prefetched by queries

Description

oci_set_prefetch ( resource $statement , int $rows ) : bool

Sets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.

Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.

Call oci_set_prefetch() before calling oci_execute().

A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.

Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 (or later) Client libraries. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2 or greater.

Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.

When using Oracle Database 12c, the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Parameters

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

rows

The number of rows to be prefetched, >= 0

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.3.2 (PECL OCI8 1.4) Before this release, rows must be >= 1.
5.3.0 (PECL OCI8 1.3.4) Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.

Examples

Example #1 Changing the default prefetch value for a query

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'SELECT * FROM myverybigtable');
oci_set_prefetch($stid300);  // Set before calling oci_execute()
oci_execute($stid);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($stidOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>".($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Changing the default prefetch for a REF CURSOR fetch

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'BEGIN myproc(:rc); END;');
$refcur oci_new_cursor($conn);
oci_bind_by_name($stid':rc'$refcur, -1OCI_B_CURSOR);
oci_execute($stid);

// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 or later Client libraries
oci_set_prefetch($refcur200);
oci_execute($refcur);

echo 
"<table border='1'>\n";
while (
$row oci_fetch_array($refcurOCI_ASSOC+OCI_RETURN_NULLS)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"    <td>".($item !== null htmlentities($itemENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back to a second PL/SQL procedure for further processing, then set the REF CURSOR prefetch count to 0 to avoid rows being "lost" from the result set. The prefetch value is the number of extra rows fetched in each OCI8 internal request to the database, so setting it to 0 means only fetch one row at a time.

Example #3 Setting the prefetch value when passing a REF CURSOR back to Oracle

<?php

$conn 
oci_connect('hr''welcome''localhost/orcl');

// get the REF CURSOR
$stid oci_parse($conn'BEGIN myproc(:rc_out); END;');
$refcur oci_new_cursor($conn);
oci_bind_by_name($stid':rc_out'$refcur, -1OCI_B_CURSOR);
oci_execute($stid);

// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur0);
oci_execute($refcur);
$row oci_fetch_array($refcur);
var_dump($row);
$row oci_fetch_array($refcur);
var_dump($row);

// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid oci_parse($conn'begin myproc_use_rc(:rc_in); end;'); 
oci_bind_by_name($stid':rc_in'$refcur, -1OCI_B_CURSOR);
oci_execute($stid);

?>

See Also



oci_statement_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_statement_typeReturns the type of a statement

Description

oci_statement_type ( resource $statement ) : string

Returns a keyword identifying the type of the OCI8 statement.

Parameters

statement

A valid OCI8 statement identifier from oci_parse().

Return Values

Returns the type of statement as one of the following strings.
Statement type
Return String Notes
ALTER  
BEGIN  
CALL Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
CREATE  
DECLARE  
DELETE  
DROP  
INSERT  
SELECT  
UPDATE  
UNKNOWN  

Returns FALSE on error.

Examples

Example #1 oci_statement_type() example

<?php

$conn 
oci_connect('hr''welcome''localhost/XE');

$stid oci_parse($conn'DELETE FROM departments WHERE department_id = 130;');
if (
oci_statement_type($stid) == "DELETE") {
    
trigger_error('You are not allowed to delete from this table'E_USER_ERROR);
}
else {
    
oci_execute($stid);  // delete the row
}

oci_free_statement($stid);
oci_close($conn);

?>



oci_unregister_taf_callback

(PHP 7.0 >= 7.0.23, PHP 7 >= 7.1.9, PECL OCI8 >= 2.1.7)

oci_unregister_taf_callbackUnregister a user-defined callback function for Oracle Database TAF

Description

oci_unregister_taf_callback ( resource $connection ) : bool

Unregister the user-defined callback function registered to connection by oci_register_taf_callback(). See OCI8 Transparent Application Failover (TAF) Support for information.

Parameters

connection

An Oracle connection identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also


Table of Contents



The OCI-Collection class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introduction

OCI8 Collection functionality.

Class synopsis

OCI-Collection {
/* Methods */
append ( mixed $value ) : bool
assign ( OCI-Collection $from ) : bool
assignElem ( int $index , mixed $value ) : bool
free ( void ) : bool
getElem ( int $index ) : mixed
max ( void ) : int
size ( void ) : int
trim ( int $num ) : bool
}

OCI-Collection::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::appendAppends element to the collection

Description

OCI-Collection::append ( mixed $value ) : bool

Appends element to the end of the collection.

Parameters

value

The value to be added to the collection. Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Collection::assign

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assignAssigns a value to the collection from another existing collection

Description

OCI-Collection::assign ( OCI-Collection $from ) : bool

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

Parameters

from

An instance of OCI-Collection.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Collection::assignElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assignElemAssigns a value to the element of the collection

Description

OCI-Collection::assignElem ( int $index , mixed $value ) : bool

Assigns a value to the element with index index.

Parameters

index

The element index. First index is 0.

value

Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Collection::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::freeFrees the resources associated with the collection object

Description

OCI-Collection::free ( void ) : bool

Frees the resources associated with the collection object.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Collection::getElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::getElemReturns value of the element

Description

OCI-Collection::getElem ( int $index ) : mixed

Returns element's value with the index index (0-based).

Parameters

index

The element index. First index is 0.

Return Values

Returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.



OCI-Collection::max

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::maxReturns the maximum number of elements in the collection

Description

OCI-Collection::max ( void ) : int

Returns the maximum number of elements in the collection.

Return Values

Returns the maximum number as an integer, or FALSE on errors.

If the returned value is 0, then the number of elements is not limited.



OCI-Collection::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::sizeReturns size of the collection

Description

OCI-Collection::size ( void ) : int

Returns the size of the collection.

Return Values

Returns the number of elements in the collection or FALSE on error.



OCI-Collection::trim

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::trimTrims elements from the end of the collection

Description

OCI-Collection::trim ( int $num ) : bool

Trims num of elements from the end of the collection.

Parameters

num

The number of elements to be trimmed.

Return Values

Returns TRUE on success or FALSE on failure.


Table of Contents



The OCI-Lob class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introduction

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

Class synopsis

OCI-Lob {
/* Methods */
append ( OCI-Lob $lob_from ) : bool
close ( void ) : bool
eof ( void ) : bool
erase ([ int $offset [, int $length ]] ) : int
export ( string $filename [, int $start [, int $length ]] ) : bool
flush ([ int $flag ] ) : bool
free ( void ) : bool
getBuffering ( void ) : bool
import ( string $filename ) : bool
load ( void ) : string
read ( int $length ) : string
rewind ( void ) : bool
save ( string $data [, int $offset ] ) : bool
seek ( int $offset [, int $whence = OCI_SEEK_SET ] ) : bool
setBuffering ( bool $on_off ) : bool
size ( void ) : int
tell ( void ) : int
truncate ([ int $length = 0 ] ) : bool
write ( string $data [, int $length ] ) : int
writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] ) : bool
}

OCI-Lob::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::appendAppends data from the large object to another large object

Description

OCI-Lob::append ( OCI-Lob $lob_from ) : bool

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob::flush before disabling buffering.

Parameters

lob_from

The copied LOB.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::close

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::closeCloses LOB descriptor

Description

OCI-Lob::close ( void ) : bool

Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob::writeTemporary.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::eof

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::eofTests for end-of-file on a large object's descriptor

Description

OCI-Lob::eof ( void ) : bool

Tells whether the internal pointer of large object is at the end of LOB.

Return Values

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

Notes

Note:

This function will return an Oracle error if OCI-Lob::setBuffering is enabled on the LOB.

See Also



OCI-Lob::erase

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::eraseErases a specified portion of the internal LOB data

Description

OCI-Lob::erase ([ int $offset [, int $length ]] ) : int

Erases a specified portion of the internal LOB data starting at a specified offset. If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

Parameters

offset

length

Return Values

Returns the actual number of characters/bytes erased or FALSE on failure.



OCI-Lob::export

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::exportExports LOB's contents to a file

Description

OCI-Lob::export ( string $filename [, int $start [, int $length ]] ) : bool

Exports LOB contents to a file.

Parameters

filename

Path to the file.

start

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



OCI-Lob::flush

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::flushFlushes/writes buffer of the LOB to the server

Description

OCI-Lob::flush ([ int $flag ] ) : bool

OCI-Lob::flush() actually writes data to the server.

Parameters

flag

By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

Return Values

Returns TRUE on success or FALSE on failure.

Returns FALSE if buffering was not enabled or an error occurred.



OCI-Lob::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::freeFrees resources associated with the LOB descriptor

Description

OCI-Lob::free ( void ) : bool

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::getBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::getBufferingReturns current state of buffering for the large object

Description

OCI-Lob::getBuffering ( void ) : bool

Tells whether the buffering for the large object is on or off.

Return Values

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.



OCI-Lob::import

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::importImports file data to the LOB

Description

OCI-Lob::import ( string $filename ) : bool

Writes data from the filename in to the current position of large object.

Parameters

filename

Path to the file.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::load

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::loadReturns large object's contents

Description

OCI-Lob::load ( void ) : string

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob::read instead.

Return Values

Returns the contents of the object, or FALSE on errors.

See Also



OCI-Lob::read

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::readReads part of the large object

Description

OCI-Lob::read ( int $length ) : string

Reads length bytes from the current position of LOB's internal pointer.

Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.

Parameters

length

The length of data to read, in bytes. Large values will be rounded down to 1 MB.

Return Values

Returns the contents as a string, or FALSE on failure.



OCI-Lob::rewind

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::rewindMoves the internal pointer to the beginning of the large object

Description

OCI-Lob::rewind ( void ) : bool

Sets the internal pointer to the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::save

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::saveSaves data to the large object

Description

OCI-Lob::save ( string $data [, int $offset ] ) : bool

Saves data to the large object.

Parameters

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::saveFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::saveFileAlias of OCI-Lob::import()

Description

This function is an alias of: OCI-Lob::import().



OCI-Lob::seek

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::seekSets the internal pointer of the large object

Description

OCI-Lob::seek ( int $offset [, int $whence = OCI_SEEK_SET ] ) : bool

Sets the internal pointer of the large object.

Parameters

offset

Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence.

whence

May be one of:

  • OCI_SEEK_SET - sets the position equal to offset
  • OCI_SEEK_CUR - adds offset bytes to the current position
  • OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object)

Return Values

Returns TRUE on success or FALSE on failure.



OCI-Lob::setBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::setBufferingChanges current state of buffering for the large object

Description

OCI-Lob::setBuffering ( bool $on_off ) : bool

Sets the buffering for the large object, depending on the value of the on_off parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. OCI-Lob::flush() should be used to flush buffers, when you have finished working with the large object.

Parameters

on_off

TRUE for on and FALSE for off.

Return Values

Returns TRUE on success or FALSE on failure. Repeated calls to this method with the same flag will return TRUE.



OCI-Lob::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::sizeReturns size of large object

Description

OCI-Lob::size ( void ) : int

Gets the size of the large object.

Return Values

Returns length of large object value or FALSE on failure. Empty objects have zero length.



OCI-Lob::tell

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::tellReturns the current position of internal pointer of large object

Description

OCI-Lob::tell ( void ) : int

Gets the current position of a LOB's internal pointer.

Return Values

Returns current position of a LOB's internal pointer or FALSE if an error occurred.



OCI-Lob::truncate

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::truncateTruncates large object

Description

OCI-Lob::truncate ([ int $length = 0 ] ) : bool

Truncates the LOB.

Parameters

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completely purge the LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



OCI-Lob::write

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeWrites data to the large object

Description

OCI-Lob::write ( string $data [, int $length ] ) : int

Writes data from the parameter data into the current position of LOB's internal pointer.

Parameters

data

The data to write in the LOB.

length

If this parameter is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

Returns the number of bytes written or FALSE on failure.

See Also



OCI-Lob::writeTemporary

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeTemporaryWrites a temporary large object

Description

OCI-Lob::writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] ) : bool

Creates a temporary large object and writes data to it.

You should use OCI-Lob::close when you are done with this object.

Parameters

data

The data to write.

lob_type

Can be one of the following:

  • OCI_TEMP_BLOB is used to create temporary BLOBs
  • OCI_TEMP_CLOB is used to create temporary CLOBs

Return Values

Returns TRUE on success or FALSE on failure.

See Also



OCI-Lob::writeToFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeToFileAlias of OCI-Lob::export()

Description

This function is an alias of: OCI-Lob::export().


Table of Contents



OCI8 Obsolete Aliases and Functions


ocibindbyname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocibindbynameAlias of oci_bind_by_name()

Description

Alias of oci_bind_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicancel

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicancelAlias of oci_cancel()

Description

Alias of oci_cancel()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicloselob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ocicloselobAlias of OCI-Lob::close()

Description

Alias of OCI-Lob::close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollappendAlias of OCI-Collection::append()

Description

Alias of OCI-Collection::append()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollassign

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ocicollassignAlias of OCI-Collection::assign()

Description

Alias of OCI-Collection::assign()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollassignelemAlias of OCI-Collection::assignElem()

Description

Alias of OCI-Collection::assignElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollgetelemAlias of OCI-Collection::getElem()

Description

Alias of OCI-Collection::getElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollmaxAlias of OCI-Collection::max()

Description

Alias of OCI-Collection::max()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollsizeAlias of OCI-Collection::size()

Description

Alias of OCI-Collection::size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolltrimAlias of OCI-Collection::trim()

Description

Alias of OCI-Collection::trim()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumnisnull

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnisnullAlias of oci_field_is_null()

Description

Alias of oci_field_is_null()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumnname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnnameAlias of oci_field_name()

Description

Alias of oci_field_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumnprecision

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnprecisionAlias of oci_field_precision()

Description

Alias of oci_field_precision()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumnscale

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnscaleAlias of oci_field_scale()

Description

Alias of oci_field_scale()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumnsize

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumnsizeAlias of oci_field_size()

Description

Alias of oci_field_size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumntype

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumntypeAlias of oci_field_type()

Description

Alias of oci_field_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicolumntyperaw

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolumntyperawAlias of oci_field_type_raw()

Description

Alias of oci_field_type_raw()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocicommit

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicommitAlias of oci_commit()

Description

Alias of oci_commit()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocidefinebyname

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocidefinebynameAlias of oci_define_by_name()

Description

Alias of oci_define_by_name()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocierror

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocierrorAlias of oci_error()

Description

Alias of oci_error()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociexecute

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociexecuteAlias of oci_execute()

Description

Alias of oci_execute()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifetch

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetchAlias of oci_fetch()

Description

Alias of oci_fetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifetchinto

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetchintoObsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

Description

Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifetchstatement

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifetchstatementAlias of oci_fetch_all()

Description

Alias of oci_fetch_all()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreecollectionAlias of OCI-Collection::free()

Description

Alias of OCI-Collection::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifreecursor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreecursorAlias of oci_free_statement()

Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifreedesc

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreedescAlias of OCI-Lob::free()

Description

Alias of OCI-Lob::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocifreestatement

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreestatementAlias of oci_free_statement()

Description

Alias of oci_free_statement()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociinternaldebug

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociinternaldebugAlias of oci_internal_debug()

Description

Alias of oci_internal_debug()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociloadlob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociloadlobAlias of OCI-Lob::load()

Description

Alias of OCI-Lob::load()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocilogoff

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocilogoffAlias of oci_close()

Description

Alias of oci_close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocilogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocilogonAlias of oci_connect()

Description

Alias of oci_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewcollectionAlias of oci_new_collection()

Description

Alias of oci_new_collection()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocinewcursor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewcursorAlias of oci_new_cursor()

Description

Alias of oci_new_cursor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocinewdescriptor

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinewdescriptorAlias of oci_new_descriptor()

Description

Alias of oci_new_descriptor()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocinlogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinlogonAlias of oci_new_connect()

Description

Alias of oci_new_connect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocinumcols

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocinumcolsAlias of oci_num_fields()

Description

Alias of oci_num_fields()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociparse

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociparseAlias of oci_parse()

Description

Alias of oci_parse()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociplogon

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociplogonAlias of oci_pconnect()

Description

Alias of oci_pconnect()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociresult

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociresultAlias of oci_result()

Description

Alias of oci_result()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocirollback

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocirollbackAlias of oci_rollback()

Description

Alias of oci_rollback()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocirowcount

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocirowcountAlias of oci_num_rows()

Description

Alias of oci_num_rows()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocisavelob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelobAlias of OCI-Lob::save()

Description

Alias of OCI-Lob::save()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocisavelobfile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelobfileAlias of OCI-Lob::import()

Description

Alias of OCI-Lob::import()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociserverversion

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociserverversionAlias of oci_server_version()

Description

Alias of oci_server_version()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocisetprefetch

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisetprefetchAlias of oci_set_prefetch()

Description

Alias of oci_set_prefetch()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ocistatementtype

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocistatementtypeAlias of oci_statement_type()

Description

Alias of oci_statement_type()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociwritelobtofile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociwritelobtofileAlias of OCI-Lob::export()

Description

Alias of OCI-Lob::export()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.



ociwritetemporarylob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ociwritetemporarylobAlias of OCI-Lob::writeTemporary()

Description

Alias of OCI-Lob::writeTemporary()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Table of Contents




Paradox File Access


Introduction

This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.

Note:

This module is also in development and may change, though major changes to the API are not expected.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.



Installing/Configuring

Table of Contents


Requirements

You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at » http://pxlib.sourceforge.net.



Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/paradox

Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

px_new() creates a new Paradox object required by all Paradox functions.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following two tables lists all constants defined by the paradox extension.
Contants for field types
Name Meaning
PX_FIELD_ALPHA Character data with fixed length
PX_FIELD_DATE Date, number of days since 1.1.0000
PX_FIELD_SHORT Short integer (2 Bytes)
PX_FIELD_LONG Long integer (4 Bytes)
PX_FIELD_CURRENCY same as PX_FIELD_NUMBER
PX_FIELD_NUMBER Double
PX_FIELD_LOGICAL Boolean
PX_FIELD_MEMOBLOB Binary large object
PX_FIELD_BLOB Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB Binary large object
PX_FIELD_OLE OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC Graphic (basically a blob, not supported)
PX_FIELD_TIME time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES Array of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER Turn all field names into lower case
PX_KEYTOUPPER Turn all field names into upper case
Contants for file types
Name Meaning
PX_FILE_INDEX_DB Indexed database
PX_FILE_PRIM_INDEX Primary index
PX_FILE_NON_INDEX_DB None indexed database
PX_FILE_NON_INC_SEC_INDEX None incremental secondary index
PX_FILE_SEC_INDEX Secondary index
PX_FILE_INC_SEC_INDEX Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G Non incremental secondary index
PX_FILE_SEC_INDEX_G Secondary index
PX_FILE_INC_SEC_INDEX_G Non incremental secondary index



Paradox Functions

Object oriented API

The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.
Methods of class paradox_db
Name of method Equivalent function
Constructor px_new()
Destructor px_delete()
open_fp() px_open_fp()
create_fp() px_create_fp()
close() px_close()
numrecords() px_numrecords()
numfields() px_numfields()
get_record() px_get_record()
put_record() px_put_record()
retrieve_record() px_retrieve_record()
delete_record() px_delete_record()
insert_record() px_insert_record()
update_record() px_update_record()
get_field() px_get_field()
get_schema() px_get_schema()
get_info() px_get_info()
set_parameter() px_set_parameter()
get_parameter() px_get_parameter()
set_value() px_set_value()
get_value() px_get_value()
get_info() px_get_info()
set_targetencoding() px_set_targetencoding()
set_tablename() px_set_tablename()
set_blob_file() px_set_blob_file()
date2string() px_date2string()
timestamp2string() px_timestamp2string()


px_close

(PECL paradox >= 1.0.0)

px_closeCloses a paradox database

Description

px_close ( resource $pxdoc ) : bool

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also



px_create_fp

(PECL paradox >= 1.0.0)

px_create_fpCreate a new paradox database

Description

px_create_fp ( resource $pxdoc , resource $file , array $fielddesc ) : bool

Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.

Note:

Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Note:

This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

File handle as returned by fopen().

fielddesc

fielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a Paradox database with two fields

<?php
if(!$pxdoc px_new()) {
  
/* Error handling */
}
$fp fopen("test.db""w+");
$fields = array(array("col1""S"), array("col2""I"));
if(!
px_create_fp($pxdoc$fp$fields)) {
  
/* Error handling */
}
px_set_parameter($pxdoc"tablename""testtable");
for(
$i=-50$i<50$i++) {
  
$rec = array($i, -$i);
  
px_put_record($pxdoc$rec);
}   
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

See Also



px_date2string

(PECL paradox >= 1.4.0)

px_date2string Converts a date into a string

Description

px_date2string ( resource $pxdoc , int $value , string $format ) : string

Turns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

value

Value as stored in paradox database field of type PX_FIELD_DATE.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox date into a human readable form

<?php
$px 
px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px$days"n/d/Y")."\n";

px_delete($px);
?>

The above example will output:

   7/15/1917
   7/15/1917
   

See Also



px_delete_record

(PECL paradox >= 1.4.0)

px_delete_recordDeletes record from paradox database

Description

px_delete_record ( resource $pxdoc , int $num ) : bool

This function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.



px_delete

(PECL paradox >= 1.0.0)

px_deleteDeletes resource of paradox database

Description

px_delete ( resource $pxdoc ) : bool

Deletes the resource of the paradox file and frees all memory.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.



px_get_field

(PECL paradox >= 1.0.0)

px_get_fieldReturns the specification of a single field

Description

px_get_field ( resource $pxdoc , int $fieldno ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

fieldno

Number of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.

Return Values

Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.



px_get_info

(PECL paradox >= 1.0.0)

px_get_infoReturn lots of information about a paradox file

Description

px_get_info ( resource $pxdoc ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.

fileversion

Version of file multiplied by 10, e.g. 70.

tablename

Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

recordsize

Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.

numdatablocks

The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.

numindexfields

Number of fields used for the primary index. The fields do always start with field number 1.

codepage

The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().

See Also



px_get_parameter

(PECL paradox >= 1.1.0)

px_get_parameterGets a parameter

Description

px_get_parameter ( resource $pxdoc , string $name ) : string

Gets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.

inputencoding

The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.

Return Values

Returns the value of the parameter or FALSE on failure.



px_get_record

(PECL paradox >= 1.0.0)

px_get_recordReturns record of paradox database

Description

px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys of the returned array into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp (PX_FIELD_TIMESTAMP) and date (PX_FIELD_DATE) are floating point respectively int values counting milliseconds respectively days starting at the beginning of julian calendar. Use the functions px-timestamp2string() and px-date2string() to convert them into a character representation.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also



px_get_schema

(PECL paradox >= 1.0.0)

px_get_schemaReturns the database schema

Description

px_get_schema ( resource $pxdoc [, int $mode = 0 ] ) : array

px_get_schema() returns the database schema.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

mode

If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of the returned array will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.

Return Values

Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types. size is the number of bytes this field consumes in the record. The total of all field sizes is equal to the record size as it can be retrieved with px-get-info().



px_get_value

(PECL paradox >= 1.1.0)

px_get_valueGets a value

Description

px_get_value ( resource $pxdoc , string $name ) : float

Gets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

Return Values

Returns the value of the parameter or FALSE on failure.



px_insert_record

(PECL paradox >= 1.4.0)

px_insert_recordInserts record into paradox database

Description

px_insert_record ( resource $pxdoc , array $data ) : int

Inserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.

Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

Return Values

Returns FALSE on failure or the record number in case of success.

Examples

Example #1 Set the date/time fields in a paradox database to the current date/time

<?php
$px 
px_new();
$fp fopen("test.db""w+");
px_create_fp($px$fp, array(array("timestamp""@"), array("time""T"), array("date""D")));

$curdate getdate();
$jd gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days $jd 1721425/* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs $curdate["hours"]*3600 $curdate["minutes"]*60 $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 $secs*1000.0$secs*1000.0$days));

$curtimestamp microtime(true);
$days = (int) ($curtimestamp/86400);
$secs $curtimestamp - ($days 86400.0);
$days += 2440588/* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425/* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 $secs*1000.0$secs*1000.0$days));
for(
$i=0$i<2$i++) {
    
$rec px_retrieve_record($px$i);
    echo 
px_timestamp2string($px$rec["timestamp"], "n/d/Y H:i:s")."\n";
    echo 
px_date2string($px$rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?>

The above example will output:

   2/21/2006 21:42:30
   2/21/2006
   2/21/2006 20:42:30
   2/21/2006
   

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

See Also

px_update_record() - Updates record in paradox database



px_new

(PECL paradox >= 1.0.0)

px_newCreate a new paradox object

Description

px_new ( void ) : resource

Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it just creates an instance of a paradox object. This function must not be called if the object oriented interface is used. Use new paradox_db() instead.

Return Values

Returns FALSE on failure.

Examples

Example #1 Opening a Paradox database

<?php
if(!$pxdoc px_new()) {
  
/* Error handling */
}
$fp fopen("test.db""r");
if(!
px_open_fp($pxdoc$fp)) {
  
/* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

If you prefer the object oriented API, then the above example will look like the following.

Example #2 Opening a Paradox database

<?php
$fp 
fopen("test.db""r");
$pxdoc = new paradox_db();
if(!
$pxdoc->open_fp($fp)) {
  
/* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

See Also



px_numfields

(PECL paradox >= 1.0.0)

px_numfieldsReturns number of fields in a database

Description

px_numfields ( resource $pxdoc ) : int

Get the number of fields in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the array returned by px_get_info().



px_numrecords

(PECL paradox >= 1.0.0)

px_numrecordsReturns number of records in a database

Description

px_numrecords ( resource $pxdoc ) : int

Get the number of records in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the array returned by px_get_info().



px_open_fp

(PECL paradox >= 1.0.0)

px_open_fpOpen paradox database

Description

px_open_fp ( resource $pxdoc , resource $file ) : bool

Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

file is the return value from fopen() with the actual database file as parameter. Make sure the database is writable if you plan to update or insert records.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fopen() - Opens file or URL
  • The example at px_new() - Create a new paradox object



px_put_record

(PECL paradox >= 1.0.0)

px_put_recordStores record into paradox database

Description

px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ] ) : bool

Stores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

record

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

recpos

This optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.

Return Values

Returns TRUE on success or FALSE on failure.



px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_recordReturns record of paradox database

Description

px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] ) : array

This function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also



px_set_blob_file

(PECL paradox >= 1.3.0)

px_set_blob_fileSets the file where blobs are read from

Description

px_set_blob_file ( resource $pxdoc , string $filename ) : bool

Sets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.

Calling px_put_record(), px_insert_record(), or px_update_record() without calling px_set_blob_file() will result in truncated blob fields unless the data fits into the database file.

Calling this function twice will close the first blob file and open the new one.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Return Values

Returns TRUE on success or FALSE on failure.



px_set_parameter

(PECL paradox >= 1.1.0)

px_set_parameterSets a parameter

Description

px_set_parameter ( resource $pxdoc , string $name , string $value ) : bool

Sets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

Depending on the parameter you want to set, name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

The value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • px_get_info() - Return lots of information about a paradox file to determine the DOS code page.



px_set_tablename

(PECL paradox >= 1.0.0)

px_set_tablenameSets the name of a table (deprecated)

Description

px_set_tablename ( resource $pxdoc , string $name ) : void

Sets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

tablename

The name of the table. If it is not set explicitly it will be set to the name of the database file.

Return Values

Returns NULL on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter



px_set_targetencoding

(PECL paradox >= 1.0.0)

px_set_targetencodingSets the encoding for character fields (deprecated)

Description

px_set_targetencoding ( resource $pxdoc , string $encoding ) : bool

Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database file. The encoding can be any string identifier known to iconv or recode. On Unix systems run iconv -l for a list of available encodings.

This function is deprecated and should be replaced by calling px_set_parameter().

See also px_get_info() to determine the DOS code page as stored in the database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

encoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

Return Values

Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.

See Also

px_set_parameter() - Sets a parameter



px_set_value

(PECL paradox >= 1.1.0)

px_set_valueSets a value

Description

px_set_value ( resource $pxdoc , string $name , float $value ) : bool

Sets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter



px_timestamp2string

(PECL paradox >= 1.4.0)

px_timestamp2string Converts the timestamp into a string

Description

px_timestamp2string ( resource $pxdoc , float $value , string $format ) : string

Turns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of miliseconds since 0001-01-02. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.

Parameters

pxdoc

Resource identifier of the paradox database.

value

Value as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox timestamp into a human readable form

<?php
$px 
px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";

/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in miliseconds since 0001-01-02 */
$stamp $days 86400.0 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px$stamp"n/d/Y H:i:s")."\n";

px_delete($px);
?>

The above example will output:

   7/15/1917
   7/15/1917 01:00:00
   

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain miliseconds.

See Also



px_update_record

(PECL paradox >= 1.4.0)

px_update_recordUpdates record in paradox database

Description

px_update_record ( resource $pxdoc , array $data , int $num ) : bool

Updates an exiting record in the database. The record starts at 0.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated array containing the field values as returned by px_retrieve_record().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_insert_record() - Inserts record into paradox database


Table of Contents




PostgreSQL


Introduction

PostgreSQL database is an Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.



Installing/Configuring

Table of Contents


Requirements

To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at » http://www.postgresql.org/ and the » PostgreSQL Documentation.



Installation

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PostgreSQL configuration options
Name Default Changeable Changelog
pgsql.allow_persistent "1" PHP_INI_SYSTEM  
pgsql.max_persistent "-1" PHP_INI_SYSTEM  
pgsql.max_links "-1" PHP_INI_SYSTEM  
pgsql.auto_reset_persistent "0" PHP_INI_SYSTEM Available since PHP 4.2.0.
pgsql.ignore_notice "0" PHP_INI_ALL Available since PHP 4.3.0.
pgsql.log_notice "0" PHP_INI_ALL Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.



Resource Types

There are two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PGSQL_LIBPQ_VERSION (string)
Short libpq version that contains only numbers and dots.
PGSQL_LIBPQ_VERSION_STR (string)
Long libpq version that includes compiler information.
PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
PGSQL_BOTH (integer)
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
PGSQL_CONNECT_FORCE_NEW (integer)
Passed to pg_connect() to force the creation of a new connection, rather than re-using an existing identical connection.
PGSQL_CONNECT_ASYNC (integer)
Passed to pg_connect() to create an asynchronous connection. Added in PHP 5.6.0.
PGSQL_CONNECTION_AUTH_OK (integer)
Available since PHP 5.6.0.
PGSQL_CONNECTION_AWAITING_RESPONSE (integer)
Available since PHP 5.6.0.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
PGSQL_CONNECTION_MADE (integer)
Available since PHP 5.6.0.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database connection is in a valid state.
PGSQL_CONNECTION_SETENV (integer)
Available since PHP 5.6.0.
PGSQL_CONNECTION_SSL_STARTUP (integer)
Available since PHP 5.6.0.
PGSQL_CONNECTION_STARTED (integer)
Available since PHP 5.6.0.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
PGSQL_TRANSACTION_INTRANS (integer)
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE (integer)
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
PGSQL_DIAG_MESSAGE_PRIMARY (integer)
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
PGSQL_DIAG_MESSAGE_HINT (integer)
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
PGSQL_DIAG_STATEMENT_POSITION (integer)
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
PGSQL_DIAG_INTERNAL_POSITION (integer)
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (integer)
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
PGSQL_DIAG_CONTEXT (integer)
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PGSQL_DIAG_SOURCE_FILE (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
PGSQL_DIAG_SCHEMA_NAME (string)
Available since PHP 7.3.0.
PGSQL_DIAG_TABLE_NAME (string)
Available since PHP 7.3.0.
PGSQL_DIAG_COLUMN_NAME (string)
Available since PHP 7.3.0.
PGSQL_DIAG_DATATYPE_NAME (string)
Available since PHP 7.3.0.
PGSQL_DIAG_CONSTRAINT_NAME (string)
Available since PHP 7.3.0.
PGSQL_ERRORS_TERSE (integer)
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
PGSQL_ERRORS_DEFAULT (integer)
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
PGSQL_ERRORS_VERBOSE (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
PGSQL_NOTICE_LAST (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_NOTICE_ALL (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_NOTICE_CLEAR (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_NOT_NULL (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
PGSQL_DML_NO_CONV (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). All parameters passed as is. Manual escape is required if parameters contain user supplied data. Use pg_escape_string() for it.
PGSQL_DML_EXEC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute query by these functions.
PGSQL_DML_ASYNC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute asynchronous query by these functions.
PGSQL_DML_STRING (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Return executed query string.
PGSQL_DML_ESCAPE (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Apply escape to all parameters instead of calling pg_convert() internally. This option omits meta data look up. Query could be as fast as pg_query() and pg_send_query(). Available since PHP 5.6.0.
PGSQL_POLLING_FAILED (integer)
Returned by pg_connect_poll() to indicate that the connection attempt failed. Available since PHP 5.6.0.
PGSQL_POLLING_READING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be readable. Available since PHP 5.6.0.
PGSQL_POLLING_WRITING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be writable. Available since PHP 5.6.0.
PGSQL_POLLING_OK (integer)
Returned by pg_connect_poll() to indicate that the connection is ready to be used. Available since PHP 5.6.0.
PGSQL_POLLING_ACTIVE (integer)
Returned by pg_connect_poll() to indicate that the connection is currently active. Available since PHP 5.6.0.
PGSQL_DIAG_SEVERITY_NONLOCALIZED (integer)
The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message). This is identical to the PG_DIAG_SEVERITY field except that the contents are never localized. This is present only in versions 9.6 and later / PHP 7.3.0 and later.


Examples

Table of Contents


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

<?php
// Connecting, selecting database
$dbconn pg_connect("host=localhost dbname=publishing user=www password=foo")
    or die(
'Could not connect: ' pg_last_error());

// Performing SQL query
$query 'SELECT * FROM authors';
$result pg_query($query) or die('Query failed: ' pg_last_error());

// Printing results in HTML
echo "<table>\n";
while (
$line pg_fetch_array($resultnullPGSQL_ASSOC)) {
    echo 
"\t<tr>\n";
    foreach (
$line as $col_value) {
        echo 
"\t\t<td>$col_value</td>\n";
    }
    echo 
"\t</tr>\n";
}
echo 
"</table>\n";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>



Basic usage

These examples contain user defined functions similar to legacy MySQL functions.

Example #1 PostgreSQL user defined functions example

<?php
// This function should be needed, since PostgreSQL connection binds database.
function pg_list_dbs($db)
{
    
assert(is_resource($db));
    
$query '
SELECT
 d.datname as "Name",
 u.usename as "Owner",
 pg_encoding_to_char(d.encoding) as "Encoding"
FROM
 pg_database d LEFT JOIN pg_user u ON d.datdba = u.usesysid
ORDER BY 1;
'
;
    return 
pg_query($db$query);
}

// List tables.
function pg_list_tables($db)
{
    
assert(is_resource($db));
    
$query "
SELECT
 c.relname as \"Name\",
 CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as \"Type\",
  u.usename as \"Owner\"
FROM
 pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
WHERE
 c.relkind IN ('r','v','S','')
 AND c.relname !~ '^pg_'
ORDER BY 1;
"
;
    return 
pg_query($db$query);
}

// See also pg_meta_data(). It returns field definition as array.
function pg_list_fields($db$table)
{
    
assert(is_resource($db));
    
$query "
SELECT
 a.attname,
 format_type(a.atttypid, a.atttypmod),
 a.attnotnull,
 a.atthasdef,
 a.attnum
FROM
 pg_class c,
 pg_attribute a
WHERE
 c.relname = '"
.$table."'
 AND a.attnum > 0 AND a.attrelid = c.oid
ORDER BY a.attnum;
"
;
    return 
pg_query($db$query);
}
?>




PostgreSQL Functions

Notes

Note:

Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

Note:

Most PostgreSQL functions accept connection as the optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Note:

PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note:

PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.


pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_affected_rowsReturns number of affected records (tuples)

Description

pg_affected_rows ( resource $result ) : int

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT.

Note:

This function used to be called pg_cmdtuples().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows affected by the query. If no tuple is affected, it will return 0.

Examples

Example #1 pg_affected_rows() example

<?php
$result 
pg_query($conn"INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples pg_affected_rows($result);

echo 
$cmdtuples " tuples are affected.\n";
?>

The above example will output:

   1 tuples are affected.
   

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_num_rows() - Returns the number of rows in a result



pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_cancel_query Cancel an asynchronous query

Description

pg_cancel_query ( resource $connection ) : bool

pg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_cancel_query() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from authors; select count(*) from authors;");
  }
  
  
$res1 pg_get_result($dbconn);
  echo 
"First call to pg_get_result(): $res1\n";
  
$rows1 pg_num_rows($res1);
  echo 
"$res1 has $rows1 records\n\n";
  
  
// Cancel the currently running query.  Will be the second query if it is
  // still running.
  
pg_cancel_query($dbconn);
?>

The above example will output:

   First call to pg_get_result(): Resource id #3
   Resource id #3 has 3 records
   

See Also



pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_client_encoding Gets the client encoding

Description

pg_client_encoding ([ resource $connection ] ) : string

PostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.

Note:

This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns SQL_ASCII. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.

The function used to be called pg_clientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

The client encoding, or FALSE on error.

Examples

Example #1 pg_client_encoding() example

<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding pg_client_encoding($conn);

echo 
"Client encoding is: "$encoding"\n";
?>

The above example will output:

   Client encoding is: ISO-8859-1
   

See Also



pg_close

(PHP 4, PHP 5, PHP 7)

pg_closeCloses a PostgreSQL connection

Description

pg_close ([ resource $connection ] ) : bool

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

Note:

Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.

If there is open large object resource on the connection, do not close the connection before closing all large object resources.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_close() example

<?php
$dbconn 
pg_connect("host=localhost port=5432 dbname=mary")
   or die(
"Could not connect");
echo 
"Connected successfully";
pg_close($dbconn);
?>

The above example will output:

   Connected successfully
   

See Also



pg_connect_poll

(PHP 5 >= 5.6.0, PHP 7)

pg_connect_poll Poll the status of an in-progress asynchronous PostgreSQL connection attempt

Description

pg_connect_poll ( resource $connection ) : int

pg_connect_poll() polls the status of a PostgreSQL connection created by calling pg_connect() with the PGSQL_CONNECT_ASYNC option.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns PGSQL_POLLING_FAILED, PGSQL_POLLING_READING, PGSQL_POLLING_WRITING, PGSQL_POLLING_OK, or PGSQL_POLLING_ACTIVE.



pg_connect

(PHP 4, PHP 5, PHP 7)

pg_connectOpen a PostgreSQL connection

Description

pg_connect ( string $connection_string [, int $connect_type ] ) : resource

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string.

If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname (defaults to value of user), user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

The options parameter can be used to set command line parameters to be invoked by the server.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

If PGSQL_CONNECT_ASYNC is given, then the connection is established asynchronously. The state of the connection can then be checked via pg_connect_poll() or pg_connection_status().

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Changelog

Version Description
5.6.0 Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.

Examples

Example #1 Using pg_connect()

<?php
$dbconn 
pg_connect("dbname=mary");
//connect to a database named "mary"

$dbconn2 pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password

$dbconn5 pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>

See Also

  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_close() - Closes a PostgreSQL connection
  • pg_host() - Returns the host name associated with the connection
  • pg_port() - Return the port number associated with the connection
  • pg_tty() - Return the TTY name associated with the connection
  • pg_options() - Get the options associated with the connection
  • pg_dbname() - Get the database name



pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_busy Get connection is busy or not

Description

pg_connection_busy ( resource $connection ) : bool

pg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE if the connection is busy, FALSE otherwise.

Examples

Example #1 pg_connection_busy() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");
  
$bs pg_connection_busy($dbconn);
  if (
$bs) {
      echo 
'connection is busy';
  } else {
     echo 
'connection is not busy';
  }
?>

See Also



pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_reset Reset connection (reconnect)

Description

pg_connection_reset ( resource $connection ) : bool

pg_connection_reset() resets the connection. It is useful for error recovery.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_connection_reset() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");
  
$dbconn2 pg_connection_reset($dbconn);
  if (
$dbconn2) {
      echo 
"reset successful\n";
  } else {
      echo 
"reset failed\n";
  }
?>

See Also



pg_connection_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_status Get connection status

Description

pg_connection_status ( resource $connection ) : int

pg_connection_status() returns the status of the specified connection.

Parameters

connection

PostgreSQL database connection resource.

Return Values

PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

Examples

Example #1 pg_connection_status() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");
  
$stat pg_connection_status($dbconn);
  if (
$stat === PGSQL_CONNECTION_OK) {
      echo 
'Connection status ok';
  } else {
      echo 
'Connection status bad';
  }    
?>

See Also



pg_consume_input

(PHP 5 >= 5.6.0, PHP 7)

pg_consume_inputReads input on the connection

Description

pg_consume_input ( resource $connection ) : bool

pg_consume_input() consumes any input waiting to be read from the database server.

Parameters

connection

PostgreSQL database connection resource.

Return Values

TRUE if no error occurred, or FALSE if there was an error. Note that TRUE does not necessarily indicate that input was waiting to be read.



pg_convert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_convert Convert associative array values into forms suitable for SQL statements

Description

pg_convert ( resource $connection , string $table_name , array $assoc_array [, int $options = 0 ] ) : array

pg_convert() checks and converts the values in assoc_array into suitable values for use in an SQL statement. Precondition for pg_convert() is the existence of a table table_name which has at least as many columns as assoc_array has elements. The fieldnames in table_name must match the indices in assoc_array and the corresponding datatypes must be compatible. Returns an array with the converted values on success, FALSE otherwise.

Note:

Since PHP 5.6.0, it accepts boolean values, converting them to PostgreSQL booleans. String representations of boolean values are also supported. NULL is converted to PostgreSQL NULL.

Prior to PHP 5.6.0, if there are boolean fields in table_name don't use the constant TRUE in assoc_array. It will be converted to the string 'TRUE' which is not a valid entry for boolean fields in PostgreSQL. Use one of "t", "true", 1, "y", "yes" instead.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table against which to convert types.

assoc_array

Data to be converted.

options

Any number of PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL or PGSQL_CONV_IGNORE_NOT_NULL, combined.

Return Values

An array of converted values, or FALSE on error.

Examples

Example #1 pg_convert() example

<?php 
  $dbconn 
pg_connect('dbname=foo');
  
  
$tmp = array(
      
'author' => 'Joe Thackery',
      
'year' => 2005,
      
'title' => 'My Life, by Joe Thackery'
  
);
  
  
$vals pg_convert($dbconn'authors'$tmp);
?>

Changelog

Version Description
5.6.0 No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() can be used with any data types.

See Also



pg_copy_from

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_from Insert records into a table from an array

Description

pg_copy_from ( resource $connection , string $table_name , array $rows [, string $delimiter [, string $null_as ]] ) : bool

pg_copy_from() inserts records into a table from rows. It issues a COPY FROM SQL command internally to insert records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to copy the rows.

rows

An array of data to be copied into table_name. Each value in rows becomes a row in table_name. Each value in rows should be a delimited string of the values to insert into each field. Values should be linefeed terminated.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_copy_from() example

<?php
   $db 
pg_connect("dbname=publisher") or die("Could not connect");
   
   
$rows pg_copy_to($db$table_name);
   
   
pg_query($db"DELETE FROM $table_name");
   
   
pg_copy_from($db$table_name$rows);
?>

See Also



pg_copy_to

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_to Copy a table to an array

Description

pg_copy_to ( resource $connection , string $table_name [, string $delimiter [, string $null_as ]] ) : array

pg_copy_to() copies a table to an array. It issues COPY TO SQL command internally to retrieve records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to copy the data into rows.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

null_as

How SQL NULL values are represented in the rows. Default is \N ("\\N").

Return Values

An array with one element for each line of COPY data. It returns FALSE on failure.

Examples

Example #1 pg_copy_to() example

<?php
   $db 
pg_connect("dbname=publisher") or die("Could not connect");
   
   
$rows pg_copy_to($db$table_name);
   
   
pg_query($db"DELETE FROM $table_name");
   
   
pg_copy_from($db$table_name$rows);
?>

See Also



pg_dbname

(PHP 4, PHP 5, PHP 7)

pg_dbnameGet the database name

Description

pg_dbname ([ resource $connection ] ) : string

pg_dbname() returns the name of the database that the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the database the connection is to, or FALSE on error.

Examples

Example #1 pg_dbname() example

<?php
  error_reporting
(E_ALL);

  
pg_connect("host=localhost port=5432 dbname=mary");
  echo 
pg_dbname(); // mary
?>



pg_delete

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_delete Deletes records

Description

pg_delete ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_delete() deletes records from a table specified by the keys and values in assoc_array. If options is specified, pg_convert() is applied to assoc_array with the specified options.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_delete() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to delete rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be deleted.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_delete() example

<?php 
  $db 
pg_connect('dbname=foo');
  
// This is safe somewhat, since all values are escaped.
  // However PostgreSQL supports JSON/Array. These are not
  // safe by neither escape nor prepared query.
  
$res pg_delete($db'post_log'$_POST);
  if (
$res) {
      echo 
"POST data is deleted: $res\n";
  } else {
      echo 
"User must have sent wrong inputs\n";
  }
?>

Changelog

Version Description
5.6.0 No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements



pg_end_copy

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_end_copySync with PostgreSQL backend

Description

pg_end_copy ([ resource $connection ] ) : bool

pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_end_copy() example

<?php 
  $conn 
pg_pconnect("dbname=foo");
  
pg_query($conn"create table bar (a int4, b char(16), d float8)");
  
pg_query($conn"copy bar from stdin");
  
pg_put_line($conn"3\thello world\t4.5\n");
  
pg_put_line($conn"4\tgoodbye world\t7.11\n");
  
pg_put_line($conn"\\.\n");
  
pg_end_copy($conn);
?>

See Also

  • pg_put_line() - Send a NULL-terminated string to PostgreSQL backend



pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_bytea Escape a string for insertion into a bytea field

Description

pg_escape_bytea ([ resource $connection ], string $data ) : string

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

Note:

When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text or binary data to be inserted into a bytea column.

Return Values

A string containing the escaped data.

Changelog

Version Description
5.2.0 connection added

Examples

Example #1 pg_escape_bytea() example

<?php 
  
// Connect to the database
  
$dbconn pg_connect('dbname=foo');
  
  
// Read in a binary file
  
$data file_get_contents('image1.jpg');
  
  
// Escape the binary data
  
$escaped pg_escape_bytea($data);
  
  
// Insert it into the database
  
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>

See Also



pg_escape_identifier

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_identifier Escape a identifier for insertion into a text field

Description

pg_escape_identifier ([ resource $connection ], string $data ) : string

pg_escape_identifier() escapes a identifier (e.g. table, field names) for querying the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() must be used. For bytea type fields, pg_escape_bytea() must be used instead.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Examples

Example #1 pg_escape_identifier() example

<?php 
  
// Connect to the database
  
$dbconn pg_connect('dbname=foo');
  
  
// Escape the table name data
  
$escaped pg_escape_identifier($table_name);
  
  
// Select rows from $table_name
  
pg_query("SELECT * FROM {$escaped};");
?>

See Also



pg_escape_literal

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_literal Escape a literal for insertion into a text field

Description

pg_escape_literal ([ resource $connection ], string $data ) : string

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect(). When there is no default connection, it raises E_WARNING and returns FALSE.

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Examples

Example #1 pg_escape_literal() example

<?php 
  
// Connect to the database
  
$dbconn pg_connect('dbname=foo');
  
  
// Read in a text file (containing apostrophes and backslashes)
  
$data file_get_contents('letter.txt');
  
  
// Escape the text data
  
$escaped pg_escape_literal($data);
  
  
// Insert it into the database. Note that no quotes around {$escaped}
  
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>

See Also



pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_string Escape a string for query

Description

pg_escape_string ([ resource $connection ], string $data ) : string

pg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes. pg_escape_literal() is more preferred way to escape SQL parameters for PostgreSQL. addslashes() must not be used with PostgreSQL. If the type of the column is bytea, pg_escape_bytea() must be used instead. pg_escape_identifier() must be used to escape identifiers (e.g. table names, field names)

Note:

This function requires PostgreSQL 7.2 or later.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Changelog

Version Description
5.2.0 connection added

Examples

Example #1 pg_escape_string() example

<?php 
  
// Connect to the database
  
$dbconn pg_connect('dbname=foo');
  
  
// Read in a text file (containing apostrophes and backslashes)
  
$data file_get_contents('letter.txt');
  
  
// Escape the text data
  
$escaped pg_escape_string($data);
  
  
// Insert it into the database
  
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

See Also



pg_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_executeSends a request to execute a prepared statement with given parameters, and waits for the result

Description

pg_execute ([ resource $connection ], string $stmtname , array $params ) : resource

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Warning

Elements are converted to strings by calling this function.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_execute()

<?php
// Connect to a database named "mary"
$dbconn pg_connect("dbname=mary");

// Prepare a query for execution
$result pg_prepare($dbconn"my_query"'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result pg_execute($dbconn"my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result pg_execute($dbconn"my_query", array("Clothes Clothes Clothes"));

?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text



pg_fetch_all_columns

(PHP 5 >= 5.1.0, PHP 7)

pg_fetch_all_columnsFetches all rows in a particular result column as an array

Description

pg_fetch_all_columns ( resource $result [, int $column = 0 ] ) : array

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Return Values

An array with all values in the result column.

FALSE is returned if column is larger than the number of columns in the result, or on any other error.

Examples

Example #1 pg_fetch_all_columns() example

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT title, name, address FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

// Get an array of all author names
$arr pg_fetch_all_columns($result1);

var_dump($arr);

?>

See Also



pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_allFetches all rows from a result as an array

Description

pg_fetch_all ( resource $result [, int $result_type = PGSQL_ASSOC ] ) : array

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

An array with all rows in the result. Each row is an array of field values indexed by field name.

FALSE is returned if there are no rows in the result, or on any other error.

Examples

Example #1 PostgreSQL fetch all

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
    echo 
"An error occurred.\n";
    exit;
}

$result pg_query($conn"SELECT * FROM authors");
if (!
$result) {
    echo 
"An error occurred.\n";
    exit;
}

$arr pg_fetch_all($result);

print_r($arr);

?>

The above example will output something similar to:

   Array
   (
       [0] => Array
           (
               [id] => 1
               [name] => Fred
           )
   
       [1] => Array
           (
               [id] => 2
               [name] => Bob
           )
   
   )
   

Changelog

Version Description
7.1.0 The result_type parameter was added.

See Also



pg_fetch_array

(PHP 4, PHP 5, PHP 7)

pg_fetch_arrayFetch a row as an array

Description

pg_fetch_array ( resource $result [, int $row [, int $result_type = PGSQL_BOTH ]] ) : array

pg_fetch_array() returns an array that corresponds to the fetched row (record).

pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indices by default.

Note: This function sets NULL fields to the PHP NULL value.

pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or NULL, the next row is fetched.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_fetch_array() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example #1 pg_fetch_array() example

<?php 

$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

$arr pg_fetch_array($result0PGSQL_NUM);
echo 
$arr[0] . " <- Row 1 Author\n";
echo 
$arr[1] . " <- Row 1 E-mail\n";

// The row parameter is optional; NULL can be passed instead,
// to pass a result_type.  Successive calls to pg_fetch_array
// will return the next row.
$arr pg_fetch_array($resultNULLPGSQL_ASSOC);
echo 
$arr["author"] . " <- Row 2 Author\n";
echo 
$arr["email"] . " <- Row 2 E-mail\n";

$arr pg_fetch_array($result);
echo 
$arr["author"] . " <- Row 3 Author\n";
echo 
$arr[1] . " <- Row 3 E-mail\n";

?>

See Also



pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_assocFetch a row as an associative array

Description

pg_fetch_assoc ( resource $result [, int $row ] ) : array

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with PGSQL_ASSOC as the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

Note: This function sets NULL fields to the PHP NULL value.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or NULL, the next row is fetched.

Return Values

An array indexed associatively (by field name). Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example #1 pg_fetch_assoc() example

<?php 
$conn 
pg_connect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT id, author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

while (
$row pg_fetch_assoc($result)) {
  echo 
$row['id'];
  echo 
$row['author'];
  echo 
$row['email'];
}
?>

See Also



pg_fetch_object

(PHP 4, PHP 5, PHP 7)

pg_fetch_objectFetch a row as an object

Description

pg_fetch_object ( resource $result [, int $row [, int $result_type = PGSQL_ASSOC ]] ) : object
pg_fetch_object ( resource $result [, int $row [, string $class_name [, array $params ]]] ) : object

pg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.

Note: This function sets NULL fields to the PHP NULL value.

Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or NULL, the next row is fetched.

result_type

Ignored and deprecated.

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

An object with one attribute for each field name in the result. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example #1 pg_fetch_object() example

<?php 

$database 
"store";

$db_conn pg_connect("host=localhost port=5432 dbname=$database");
if (!
$db_conn) {
  echo 
"Failed connecting to postgres database $database\n";
  exit;
}

$qu pg_query($db_conn"SELECT * FROM books ORDER BY author");


while (
$data pg_fetch_object($qu)) {
  echo 
$data->author " (";
  echo 
$data->year "): ";
  echo 
$data->title "<br />";
}

pg_free_result($qu);
pg_close($db_conn);

?>

See Also



pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_fetch_resultReturns values from a result resource

Description

pg_fetch_result ( resource $result , int $row , mixed $field ) : string
pg_fetch_result ( resource $result , mixed $field ) : string

pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

Note:

This function used to be called pg_result().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.

field

A string representing the name of the field (column) to fetch, otherwise an int representing the field number to fetch. Fields are numbered from 0 upwards.

Return Values

Boolean is returned as "t" or "f". All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, or on any other error.

Examples

Example #1 pg_fetch_result() example

<?php
$db 
pg_connect("dbname=users user=me") || die();

$res pg_query($db"SELECT 1 UNION ALL SELECT 2");

$val pg_fetch_result($res10);

echo 
"First field in the second row is: "$val"\n";
?>

The above example will output:

   First field in the second row is: 2
   

See Also



pg_fetch_row

(PHP 4, PHP 5, PHP 7)

pg_fetch_rowGet a row as an enumerated array

Description

pg_fetch_row ( resource $result [, int $row ] ) : array

pg_fetch_row() fetches one row of data from the result associated with the specified result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or NULL, the next row is fetched.

Return Values

An array, indexed from 0 upwards, with each value represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Examples

Example #1 pg_fetch_row() example

<?php

$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

while (
$row pg_fetch_row($result)) {
  echo 
"Author: $row[0]  E-mail: $row[1]";
  echo 
"<br />\n";
}
 
?>

See Also



pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_is_nullTest if a field is SQL NULL

Description

pg_field_is_null ( resource $result , int $row , mixed $field ) : int
pg_field_is_null ( resource $result , mixed $field ) : int

pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL NULL or not.

Note:

This function used to be called pg_fieldisnull().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched.

field

Field number (starting from 0) as an integer or the field name as a string.

Return Values

Returns 1 if the field in the given row is SQL NULL, 0 if not. FALSE is returned if the row is out of range, or upon any other error.

Examples

Example #1 pg_field_is_null() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die ("Could not connect");
  
$res pg_query($dbconn"select * from authors where author = 'Orwell'");
  if (
$res) {
      if (
pg_field_is_null($res0"year") == 1) {
          echo 
"The value of the field year is null.\n";
      }
      if (
pg_field_is_null($res0"year") == 0) {
          echo 
"The value of the field year is not null.\n";
    }
 }
?>



pg_field_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_nameReturns the name of a field

Description

pg_field_name ( resource $result , int $field_number ) : string

pg_field_name() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.

Note:

This function used to be called pg_fieldname().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The field name, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
$res pg_query($dbconn"select * from authors where author = 'Orwell'");
  
$i pg_num_fields($res);
  for (
$j 0$j $i$j++) {
      echo 
"column $j\n";
      
$fieldname pg_field_name($res$j);
      echo 
"fieldname: $fieldname\n";
      echo 
"printed length: " pg_field_prtlen($res$fieldname) . " characters\n";
      echo 
"storage length: " pg_field_size($res$j) . " bytes\n";
      echo 
"field type: " pg_field_type($res$j) . " \n\n";
  }
?>

The above example will output:

   column 0
   fieldname: author
   printed length: 6 characters
   storage length: -1 bytes
   field type: varchar 
   
   column 1
   fieldname: year
   printed length: 4 characters
   storage length: 2 bytes
   field type: int2 
   
   column 2
   fieldname: title
   printed length: 24 characters
   storage length: -1 bytes
   field type: varchar 
   

See Also



pg_field_num

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_numReturns the field number of the named field

Description

pg_field_num ( resource $result , string $field_name ) : int

pg_field_num() will return the number of the field number that corresponds to the field_name in the given PostgreSQL result resource.

Note:

This function used to be called pg_fieldnum().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_name

The name of the field.

Return Values

The field number (numbered from 0), or -1 on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
$res pg_query($dbconn"select author, year, title from authors where author = 'Orwell'");
  
  echo 
"Column 'title' is field number: "pg_field_num($res'title');
?>

The above example will output:

   Column 'title' is field number: 2
   

See Also



pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_prtlenReturns the printed length

Description

pg_field_prtlen ( resource $result , int $row_number , mixed $field_name_or_number ) : int
pg_field_prtlen ( resource $result , mixed $field_name_or_number ) : int

pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL result. Row numbering starts at 0. This function will return FALSE on an error.

field_name_or_number can be passed either as an integer or as a string. If it is passed as an integer, PHP recognises it as the field number, otherwise as field name.

See the example given at the pg_field_name() page.

Note:

This function used to be called pg_fieldprtlen().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.

Return Values

The field printed length, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
$res pg_query($dbconn"select * from authors where author = 'Orwell'");
  
$i pg_num_fields($res);
  for (
$j 0$j $i$j++) {
      echo 
"column $j\n";
      
$fieldname pg_field_name($res$j);
      echo 
"fieldname: $fieldname\n";
      echo 
"printed length: " pg_field_prtlen($res$fieldname) . " characters\n";
      echo 
"storage length: " pg_field_size($res$j) . " bytes\n";
      echo 
"field type: " pg_field_type($res$j) . " \n\n";
  }
?>

The above example will output:

   column 0
   fieldname: author
   printed length: 6 characters
   storage length: -1 bytes
   field type: varchar 
   
   column 1
   fieldname: year
   printed length: 4 characters
   storage length: 2 bytes
   field type: int2 
   
   column 2
   fieldname: title
   printed length: 24 characters
   storage length: -1 bytes
   field type: varchar 
   

See Also



pg_field_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_size Returns the internal storage size of the named field

Description

pg_field_size ( resource $result , int $field_number ) : int

pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL result.

Note:

This function used to be called pg_fieldsize().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The internal field storage size (in bytes). -1 indicates a variable length field. FALSE is returned on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
$res pg_query($dbconn"select * from authors where author = 'Orwell'");
  
$i pg_num_fields($res);
  for (
$j 0$j $i$j++) {
      echo 
"column $j\n";
      
$fieldname pg_field_name($res$j);
      echo 
"fieldname: $fieldname\n";
      echo 
"printed length: " pg_field_prtlen($res$fieldname) . " characters\n";
      echo 
"storage length: " pg_field_size($res$j) . " bytes\n";
      echo 
"field type: " pg_field_type($res$j) . " \n\n";
  }
?>

The above example will output:

   column 0
   fieldname: author
   printed length: 6 characters
   storage length: -1 bytes
   field type: varchar 
   
   column 1
   fieldname: year
   printed length: 4 characters
   storage length: 2 bytes
   field type: int2 
   
   column 2
   fieldname: title
   printed length: 24 characters
   storage length: -1 bytes
   field type: varchar 
   

See Also



pg_field_table

(PHP 5 >= 5.2.0, PHP 7)

pg_field_tableReturns the name or oid of the tables field

Description

pg_field_table ( resource $result , int $field_number [, bool $oid_only = FALSE ] ) : mixed

pg_field_table() returns the name of the table that field belongs to, or the table's oid if oid_only is TRUE.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

oid_only

By default the tables name that field belongs to is returned but if oid_only is set to TRUE, then the oid will instead be returned.

Return Values

On success either the fields table name or oid. Or, FALSE on failure.

Examples

Example #1 Getting table information about a field

<?php
$dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

$res pg_query($dbconn"SELECT bar FROM foo");

echo 
pg_field_table($res0);
echo 
pg_field_table($res0true);

$res pg_query($dbconn"SELECT version()");
var_dump(pg_field_table($res0));
?>

The above example will output something similar to:

   foo
   14379580
   
   bool(false)
   

Notes

Note:

Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

See Also



pg_field_type_oid

(PHP 5 >= 5.1.0, PHP 7)

pg_field_type_oid Returns the type ID (OID) for the corresponding field number

Description

pg_field_type_oid ( resource $result , int $field_number ) : int

pg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.

You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

Note:

If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The OID of the field's base type. FALSE is returned on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Assume 'title' is a varchar type
  
$res pg_query($dbconn"select title from authors where author = 'Orwell'");

  echo 
"Title field type OID: "pg_field_type_oid($res0);
?>

The above example will output:

   Title field type OID: 1043
   

See Also



pg_field_type

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_type Returns the type name for the corresponding field number

Description

pg_field_type ( resource $result , int $field_number ) : string

pg_field_type() returns a string containing the base type name of the given field_number in the given PostgreSQL result resource.

Note:

If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.

Note:

This function used to be called pg_fieldtype().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

A string containing the base name of the field's type, or FALSE on error.

Examples

Example #1 Getting information about fields

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Assume 'title' is a varchar type
  
$res pg_query($dbconn"select title from authors where author = 'Orwell'");

  echo 
"Title field type: "pg_field_type($res0);
?>

The above example will output:

   Title field type: varchar
   

See Also



pg_flush

(PHP 5 >= 5.6.0, PHP 7)

pg_flushFlush outbound query data on the connection

Description

pg_flush ( resource $connection ) : mixed

pg_flush() flushes any outbound query data waiting to be sent on the connection.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE if the flush was successful or no data was waiting to be flushed, 0 if part of the pending data was flushed but more remains or FALSE on failure.



pg_free_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_free_resultFree result memory

Description

pg_free_result ( resource $result ) : bool

pg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

Note:

This function used to be called pg_freeresult().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_free_result() example

<?php
$db 
pg_connect("dbname=users user=me") || die();

$res pg_query($db"SELECT 1 UNION ALL SELECT 2");

$val pg_fetch_result($res10);

echo 
"First field in the second row is: "$val"\n";

pg_free_result($res);
?>

The above example will output:

   First field in the second row is: 2
   

See Also

  • pg_query() - Execute a query
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result



pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_notifyGets SQL NOTIFY message

Description

pg_get_notify ( resource $connection [, int $result_type ] ) : array

pg_get_notify() gets notifications generated by a NOTIFY SQL command. To receive notifications, the LISTEN SQL command must be issued.

Parameters

connection

PostgreSQL database connection resource.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_get_notify() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array containing the NOTIFY message name and backend PID. As of PHP 5.4.0 and if supported by the server, the array also contains the server version and the payload. Otherwise if no NOTIFY is waiting, then FALSE is returned.

Examples

Example #1 PostgreSQL NOTIFY message

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn'LISTEN author_updated;');
$notify pg_get_notify($conn);
if (!
$notify) {
  echo 
"No messages\n";
} else {
  
print_r($notify);
}
?>

See Also



pg_get_pid

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_pidGets the backend's process ID

Description

pg_get_pid ( resource $connection ) : int

pg_get_pid() gets the backend's (database server process) PID. The PID is useful to determine whether or not a NOTIFY message received via pg_get_notify() is sent from another process or not.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The backend database process ID.

Examples

Example #1 PostgreSQL backend PID

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid pg_get_pid($conn);
?>

See Also



pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_get_result Get asynchronous query result

Description

pg_get_result ([ resource $connection ] ) : resource

pg_get_result() gets the result resource from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().

pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The result resource, or FALSE if no more results are available.

Examples

Example #1 pg_get_result() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from authors; select count(*) from authors;");
  }
  
  
$res1 pg_get_result($dbconn);
  echo 
"First call to pg_get_result(): $res1\n";
  
$rows1 pg_num_rows($res1);
  echo 
"$res1 has $rows1 records\n\n";
  
  
$res2 pg_get_result($dbconn);
  echo 
"Second call to pg_get_result(): $res2\n";
  
$rows2 pg_num_rows($res2);
  echo 
"$res2 has $rows2 records\n";
?>

The above example will output:

   First call to pg_get_result(): Resource id #3
   Resource id #3 has 3 records
   
   Second call to pg_get_result(): Resource id #4
   Resource id #4 has 1 records
   

See Also



pg_host

(PHP 4, PHP 5, PHP 7)

pg_host Returns the host name associated with the connection

Description

pg_host ([ resource $connection ] ) : string

pg_host() returns the host name of the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the host the connection is to, or FALSE on error.

Examples

Example #1 pg_host() example

<?php
$pgsql_conn 
pg_connect("dbname=mark host=localhost");

if (
$pgsql_conn) {
   print 
"Successfully connected to: " pg_host($pgsql_conn) . "<br/>\n";
} else {
   print 
pg_last_error($pgsql_conn);
   exit;
}
?>

See Also



pg_insert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_insert Insert array into table

Description

pg_insert ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_insert() inserts the values of assoc_array into the table specified by table_name. If options is specified, pg_convert() is applied to assoc_array with the specified options.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_insert() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be inserted.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Return Values

Returns the connection resource on success, or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_insert() example

<?php 
  $dbconn 
pg_connect('dbname=foo');
  
// This is safe somewhat, since all values are escaped.
  // However PostgreSQL supports JSON/Array. These are not
  // safe by neither escape nor prepared query.
  
$res pg_insert($dbconn'post_log'$_POSTPG_DML_ESCAPE);
  if (
$res) {
      echo 
"POST data is successfully logged\n";
  } else {
      echo 
"User must have sent wrong inputs\n";
  }
?>

Changelog

Version Description
5.6.0 Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of TRUE on success.
5.6.0 No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements



pg_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_errorGet the last error message string of a connection

Description

pg_last_error ([ resource $connection ] ) : string

pg_last_error() returns the last error message for a given connection.

Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.

Use pg_result_error(), pg_result_error_field(), pg_result_status() and pg_connection_status() for better error handling.

Note:

This function used to be called pg_errormessage().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the last error message on the given connection, or FALSE on error.

Examples

Example #1 pg_last_error() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Query that fails
  
$res pg_query($dbconn"select * from doesnotexist");
  
  echo 
pg_last_error($dbconn);
?>

See Also



pg_last_notice

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

pg_last_notice Returns the last notice message from PostgreSQL server

Description

pg_last_notice ( resource $connection [, int $option = PGSQL_NOTICE_LAST ] ) : mixed

pg_last_notice() returns the last notice message from the PostgreSQL server on the specified connection. The PostgreSQL server sends notice messages in several cases, for instance when creating a SERIAL column in a table.

With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini. Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.

Parameters

connection

PostgreSQL database connection resource.

option

One of PGSQL_NOTICE_LAST (to return last notice), PGSQL_NOTICE_ALL (to return all notices), or PGSQL_NOTICE_CLEAR (to clear notices).

Return Values

A string containing the last notice on the given connection with PGSQL_NOTICE_LAST, an array with PGSQL_NOTICE_ALL, a boolean with PGSQL_NOTICE_CLEAR, or FALSE on error.

Examples

Example #1 pg_last_notice() example

<?php
  $pgsql_conn 
pg_connect("dbname=mark host=localhost");
  
  
$res pg_query("CREATE TABLE test (id SERIAL)");
  
  
$notice pg_last_notice($pgsql_conn);
  
  echo 
$notice;
?>

The above example will output:

   CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"
   

Changelog

Version Description
7.1.0 The option parameter was added.

See Also



pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_oidReturns the last row's OID

Description

pg_last_oid ( resource $result ) : string

pg_last_oid() is used to retrieve the OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.

To get the value of a SERIAL field in an inserted row, it is necessary to use the PostgreSQL CURRVAL function, naming the sequence whose last value is required. If the name of the sequence is unknown, the pg_get_serial_sequence PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function LASTVAL that returns the value of the most recently used sequence in the session. This avoids the need for naming the sequence, table or column altogether.

Note:

This function used to be called pg_getlastoid().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

A string containing the OID assigned to the most recently inserted row in the specified connection, or FALSE on error or no available OID.

Examples

Example #1 pg_last_oid() example

<?php
  
// Connect to the database
  
pg_connect("dbname=mark host=localhost");

  
// Create a sample table
  
pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

  
// Insert some data into it
  
$res pg_query("INSERT INTO test VALUES (1)");

  
$oid pg_last_oid($res);
?>

See Also



pg_lo_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_closeClose a large object

Description

pg_lo_close ( resource $large_object ) : bool

pg_lo_close() closes a large object. large_object is a resource for the large object from pg_lo_open().

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_loclose().

Parameters

result

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_close() example

<?php
   $database 
pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$oid pg_lo_create($database);
   echo 
"$oid\n";
   
$handle pg_lo_open($database$oid"w");
   echo 
"$handle\n";
   
pg_lo_write($handle"large object data");
   
pg_lo_close($handle);
   
pg_query($database"commit");
?>

See Also



pg_lo_create

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_createCreate a large object

Description

pg_lo_create ([ resource $connection [, mixed $object_id ]] ) : int
pg_lo_create ( mixed $object_id ) : int

pg_lo_create() creates a large object and returns the OID of the large object. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).

To use the large object interface, it is necessary to enclose it within a transaction block.

Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().

Note:

This function used to be called pg_locreate().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

A large object OID or FALSE on error.

Changelog

Version Description
5.3.0

The optional object_id was added.

Examples

Example #1 pg_lo_create() example

<?php
   $database 
pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$oid pg_lo_create($database);
   echo 
"$oid\n";
   
$handle pg_lo_open($database$oid"w");
   echo 
"$handle\n";
   
pg_lo_write($handle"large object data");
   
pg_lo_close($handle);
   
pg_query($database"commit");
?>



pg_lo_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_exportExport a large object to file

Description

pg_lo_export ([ resource $connection ], int $oid , string $pathname ) : bool

pg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_loexport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

pathname

The full path and file name of the file in which to write the large object on the client filesystem.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_export() example

<?php
   $database 
pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$oid pg_lo_create($database);
   
$handle pg_lo_open($database$oid"w");
   
pg_lo_write($handle"large object data");
   
pg_lo_close($handle);
   
pg_lo_export($database$oid'/tmp/lob.dat');
   
pg_query($database"commit");
?>

See Also



pg_lo_import

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_importImport a large object from file

Description

pg_lo_import ([ resource $connection ], string $pathname [, mixed $object_id ] ) : int

pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function used to be called pg_loimport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

pathname

The full path and file name of the file on the client filesystem from which to read the large object data.

object_id

If an object_id is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

The OID of the newly created large object, or FALSE on failure.

Changelog

Version Description
5.3.0

The optional object_id was added.

Examples

Example #1 pg_lo_import() example

<?php
   $database 
pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$oid pg_lo_import($database'/tmp/lob.dat');
   
pg_query($database"commit");
?>

See Also



pg_lo_open

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_openOpen a large object

Description

pg_lo_open ( resource $connection , int $oid , string $mode ) : resource

pg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.

Warning

Do not close the database connection before closing the large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_loopen().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

mode

Can be either "r" for read-only, "w" for write only or "rw" for read and write.

Return Values

A large object resource or FALSE on error.

Examples

Example #1 pg_lo_open() example

<?php
   $database 
pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$oid pg_lo_create($database);
   echo 
"$oid\n";
   
$handle pg_lo_open($database$oid"w");
   echo 
"$handle\n";
   
pg_lo_write($handle"large object data");
   
pg_lo_close($handle);
   
pg_query($database"commit");
?>

See Also



pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_read_all Reads an entire large object and send straight to browser

Description

pg_lo_read_all ( resource $large_object ) : int

pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_loreadall().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Number of bytes read or FALSE on error.

Examples

Example #1 pg_lo_read_all() example

<?php
   header
('Content-type: image/jpeg');
   
$image_oid 189762345;
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$image_oid"r");
   
pg_lo_read_all($handle);
   
pg_query($database"commit");
?>

See Also



pg_lo_read

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_readRead a large object

Description

pg_lo_read ( resource $large_object [, int $len = 8192 ] ) : string

pg_lo_read() reads at most len bytes from a large object and returns it as a string.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_loread().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

len

An optional maximum number of bytes to return.

Return Values

A string containing len bytes from the large object, or FALSE on error.

Examples

Example #1 pg_lo_read() example

<?php
   $doc_oid 
189762345;
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$doc_oid"r");
   
$data pg_lo_read($handle50000);
   
pg_query($database"commit");
   echo 
$data;
?>

See Also



pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_seek Seeks position within a large object

Description

pg_lo_seek ( resource $large_object , int $offset [, int $whence = PGSQL_SEEK_CUR ] ) : bool

pg_lo_seek() seeks a position within a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

offset

The number of bytes to seek.

whence

One of the constants PGSQL_SEEK_SET (seek from object start), PGSQL_SEEK_CUR (seek from current position) or PGSQL_SEEK_END (seek from object end) .

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_seek() example

<?php
   $doc_oid 
189762345;
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$doc_oid"r");
   
// Skip first 50000 bytes
   
pg_lo_seek($handle50000PGSQL_SEEK_SET);
   
// Read the next 10000 bytes
   
$data pg_lo_read($handle10000);
   
pg_query($database"commit");
   echo 
$data;
?>

Changelog

Version Description
5.6.0 Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object



pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_tell Returns current seek position a of large object

Description

pg_lo_tell ( resource $large_object ) : int

pg_lo_tell() returns the current position (offset from the beginning) of a large object.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.

Examples

Example #1 pg_lo_tell() example

<?php
   $doc_oid 
189762345;
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$doc_oid"r");
   
// Skip first 50000 bytes
   
pg_lo_seek($handle50000PGSQL_SEEK_SET);
   
// See how far we've skipped
   
$offset pg_lo_tell($handle);
   echo 
"Seek position is: $offset";
   
pg_query($database"commit");
?>

The above example will output:

   Seek position is: 50000
   

Changelog

Version Description
5.6.0 Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also



pg_lo_truncate

(PHP 5 >= 5.6.0, PHP 7)

pg_lo_truncate Truncates a large object

Description

pg_lo_truncate ( resource $large_object , int $size ) : bool

pg_lo_truncate() truncates a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

size

The number of bytes to truncate.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_lo_truncate() example

<?php
   $doc_oid 
189762345;
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$doc_oid"r");
   
// Truncate to 0
   
pg_lo_truncate($handle0);
   
pg_query($database"commit");
   echo 
$data;
?>

Changelog

Version Description
5.6.0 Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object




pg_lo_write

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_writeWrite to a large object

Description

pg_lo_write ( resource $large_object , string $data [, int $len ] ) : int

pg_lo_write() writes data into a large object at the current seek position.

To use the large object interface, it is necessary to enclose it within a transaction block.

Note:

This function used to be called pg_lowrite().

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

data

The data to be written to the large object. If len is specified and is less than the length of data, only len bytes will be written.

len

An optional maximum number of bytes to write. Must be greater than zero and no greater than the length of data. Defaults to the length of data.

Return Values

The number of bytes written to the large object, or FALSE on error.

Examples

Example #1 pg_lo_write() example

<?php
   $doc_oid 
189762345;
   
$data "This will overwrite the start of the large object.";
   
$database pg_connect("dbname=jacarta");
   
pg_query($database"begin");
   
$handle pg_lo_open($database$doc_oid"w");
   
$data pg_lo_write($handle$data);
   
pg_query($database"commit");
?>

See Also



pg_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_meta_data Get meta data for table

Description

pg_meta_data ( resource $connection , string $table_name [, bool $extended = FALSE ] ) : array

pg_meta_data() returns table definition for table_name as an array.

Parameters

connection

PostgreSQL database connection resource.

table_name

The name of the table.

extended

Flag for returning extended meta data. Default to FALSE.

Return Values

An array of the table definition, or FALSE on error.

Examples

Example #1 Getting table metadata

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
$meta pg_meta_data($dbconn'authors');
  if (
is_array($meta)) {
      echo 
'<pre>';
      
var_dump($meta);
      echo 
'</pre>';
  }
?>

The above example will output:

   array(3) {
   ["author"]=>
   array(5) {
     ["num"]=>
     int(1)
     ["type"]=>
     string(7) "varchar"
     ["len"]=>
     int(-1)
     ["not null"]=>
     bool(false)
     ["has default"]=>
     bool(false)
   }
   ["year"]=>
   array(5) {
     ["num"]=>
     int(2)
     ["type"]=>
     string(4) "int2"
     ["len"]=>
     int(2)
     ["not null"]=>
     bool(false)
     ["has default"]=>
     bool(false)
   }
   ["title"]=>
   array(5) {
     ["num"]=>
     int(3)
     ["type"]=>
     string(7) "varchar"
     ["len"]=>
     int(-1)
     ["not null"]=>
     bool(false)
     ["has default"]=>
     bool(false)
   }
   }
   

Changelog

Version Description
5.6.0 No longer experimental. Added "is enum" as default attribute. extended flag is added.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements



pg_num_fields

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_fieldsReturns the number of fields in a result

Description

pg_num_fields ( resource $result ) : int

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.

Note:

This function used to be called pg_numfields().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of fields (columns) in the result. On error, -1 is returned.

Examples

Example #1 pg_num_fields() example

<?php
$result 
pg_query($conn"SELECT 1, 2");

$num pg_num_fields($result);

echo 
$num " field(s) returned.\n";
?>

The above example will output:

   2 field(s) returned.
   

See Also



pg_num_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_rowsReturns the number of rows in a result

Description

pg_num_rows ( resource $result ) : int

pg_num_rows() will return the number of rows in a PostgreSQL result resource.

Note:

This function used to be called pg_numrows().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows in the result. On error, -1 is returned.

Examples

Example #1 pg_num_rows() example

<?php
$result 
pg_query($conn"SELECT 1");

$rows pg_num_rows($result);

echo 
$rows " row(s) returned.\n";
?>

The above example will output:

   1 row(s) returned.
   

See Also



pg_options

(PHP 4, PHP 5, PHP 7)

pg_optionsGet the options associated with the connection

Description

pg_options ([ resource $connection ] ) : string

pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the connection options, or FALSE on error.

Examples

Example #1 pg_options() example

<?php
   $pgsql_conn 
pg_connect("dbname=mark host=localhost");
   echo 
pg_options($pgsql_conn);
?>

See Also



pg_parameter_status

(PHP 5, PHP 7)

pg_parameter_statusLooks up a current parameter setting of the server

Description

pg_parameter_status ([ resource $connection ], string $param_name ) : string

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Caution

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Return Values

A string containing the value of the parameter, FALSE on failure or invalid param_name.

Examples

Example #1 pg_parameter_status() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  echo 
"Server encoding: "pg_parameter_status($dbconn"server_encoding");
?>

The above example will output:

   Server encoding: SQL_ASCII
   



pg_pconnect

(PHP 4, PHP 5, PHP 7)

pg_pconnectOpen a persistent PostgreSQL connection

Description

pg_pconnect ( string $connection_string [, int $connect_type ] ) : resource

pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.

If a second call is made to pg_pconnect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.

To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection can be defined with the pgsql.max_persistent php.ini directive (defaults to -1 for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.

pg_close() will not close persistent links generated by pg_pconnect().

Parameters

connection_string

The connection_string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., \' and \\.

The currently recognized parameter keywords are: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignored), sslmode, requiressl (deprecated in favor of sslmode), and service. Which of these arguments exist depends on your PostgreSQL version.

connect_type

If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection is created, even if the connection_string is identical to an existing connection.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example #1 Using pg_pconnect()

<?php
$dbconn 
pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password

$conn_string "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 pg_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

See Also



pg_ping

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_pingPing database connection

Description

pg_ping ([ resource $connection ] ) : bool

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_ping() example

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

if (!
pg_ping($conn))
  die(
"Connection is broken\n");
?>

See Also



pg_port

(PHP 4, PHP 5, PHP 7)

pg_port Return the port number associated with the connection

Description

pg_port ([ resource $connection ] ) : int

pg_port() returns the port number that the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

An int containing the port number of the database server the connection is to, or FALSE on error.

Examples

Example #1 pg_port() example

<?php
$pgsql_conn 
pg_connect("dbname=mark host=localhost");

if (
$pgsql_conn) {
   print 
"Successfully connected to port: " pg_port($pgsql_conn) . "<br/>\n";
} else {
   print 
pg_last_error($pgsql_conn);
   exit;
}
?>



pg_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_prepare Submits a request to create a prepared statement with the given parameters, and waits for completion

Description

pg_prepare ([ resource $connection ], string $stmtname , string $query ) : resource

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn pg_connect("dbname=mary");

// Prepare a query for execution
$result pg_prepare($dbconn"my_query"'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result pg_execute($dbconn"my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result pg_execute($dbconn"my_query", array("Clothes Clothes Clothes"));

?>

See Also

  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)



pg_put_line

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_put_lineSend a NULL-terminated string to PostgreSQL backend

Description

pg_put_line ([ resource $connection ], string $data ) : bool

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's COPY FROM command.

COPY is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction.

An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.

Note:

The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().

Warning

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A line of text to be sent directly to the PostgreSQL backend. A NULL terminator is added automatically.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_put_line() example

<?php 
  $conn 
pg_pconnect("dbname=foo");
  
pg_query($conn"create table bar (a int4, b char(16), d float8)");
  
pg_query($conn"copy bar from stdin");
  
pg_put_line($conn"3\thello world\t4.5\n");
  
pg_put_line($conn"4\tgoodbye world\t7.11\n");
  
pg_put_line($conn"\\.\n");
  
pg_end_copy($conn);
?>

See Also



pg_query_params

(PHP 5 >= 5.1.0, PHP 7)

pg_query_paramsSubmits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

Description

pg_query_params ([ resource $connection ], string $query , array $params ) : resource

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. The same parameter may appear more than once in the query; the same value will be used in that case. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Values intended for bytea fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result pg_query_params($dbconn'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str pg_escape_string("Joe's Widgets");
$result pg_query($dbconn"SELECT * FROM shops WHERE name = '{$str}'");

?>

See Also



pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_queryExecute a query

Description

pg_query ([ resource $connection ], string $query ) : resource

pg_query() executes the query on the specified database connection. pg_query_params() should be preferred in most cases.

If an error occurs, and FALSE is returned, details of the error can be retrieved using the pg_last_error() function if the connection is valid.

Note: Although connection can be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.

Note:

This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.

Warning

String interpolation of user-supplied data is extremely dangerous and is likely to lead to SQL injection vulnerabilities. In most cases pg_query_params() should be preferred, passing user-supplied values as parameters rather than substituting them into the query string.

Any user-supplied data substituted directly into a query string should be properly escaped.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 pg_query() example

<?php

$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

$result pg_query($conn"SELECT author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

while (
$row pg_fetch_row($result)) {
  echo 
"Author: $row[0]  E-mail: $row[1]";
  echo 
"<br />\n";
}
 
?>

Example #2 Using pg_query() with multiple statements

<?php

$conn 
pg_pconnect("dbname=publisher");

// these statements will be executed as one transaction

$query "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";

pg_query($conn$query);

?>

See Also



pg_result_error_field

(PHP 5 >= 5.1.0, PHP 7)

pg_result_error_fieldReturns an individual field of an error report

Description

pg_result_error_field ( resource $result , int $fieldcode ) : string

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.

Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

Parameters

result

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

Return Values

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Examples

Example #1 pg_result_error_field() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from doesnotexist;");
  }
  
  
$res1 pg_get_result($dbconn);
  echo 
pg_result_error_field($res1PGSQL_DIAG_SQLSTATE);
?>

See Also



pg_result_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_error Get error message associated with result

Description

pg_result_error ( resource $result ) : string

pg_result_error() returns any error message associated with the result resource. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns a string. Returns empty string if there is no error. If there is an error associated with the result parameter, returns FALSE.

Examples

Example #1 pg_result_error() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from doesnotexist;");
  }
  
  
$res1 pg_get_result($dbconn);
  echo 
pg_result_error($res1);
?>

See Also



pg_result_seek

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_result_seekSet internal row offset in result resource

Description

pg_result_seek ( resource $result , int $offset ) : bool

pg_result_seek() sets the internal row offset in a result resource.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

offset

Row to move the internal offset to in the result resource. Rows are numbered starting from zero.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_result_seek() example

<?php

// Connect to the database
$conn pg_pconnect("dbname=publisher");

// Execute a query
$result pg_query($conn"SELECT author, email FROM authors");

// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result2);

// Fetch the 3rd row
$row pg_fetch_row($result);
 
?>

See Also



pg_result_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_status Get status of query result

Description

pg_result_status ( resource $result [, int $type = PGSQL_STATUS_LONG ] ) : mixed

pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

type

Either PGSQL_STATUS_LONG to return the numeric status of the result, or PGSQL_STATUS_STRING to return the command tag of the result. If not specified, PGSQL_STATUS_LONG is the default.

Return Values

Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is specified. Otherwise, a string containing the PostgreSQL command tag is returned.

Examples

Example #1 pg_result_status() example

<?php

// Connect to the database
$conn pg_pconnect("dbname=publisher");

// Execute a COPY
$result pg_query($conn"COPY authors FROM STDIN;");

// Get the result status
$status pg_result_status($result);

// Determine status
if ($status == PGSQL_COPY_IN)
   echo 
"Copy began.";
else
   echo 
"Copy failed.";
 
?>

The above example will output:

   Copy began.
   

See Also



pg_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_select Select records

Description

pg_select ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC [, int $result_type = PGSQL_ASSOC ]] ) : mixed

pg_select() selects records specified by assoc_array which has field=>value. For a successful query, it returns an array containing all records and fields that match the condition specified by assoc_array.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_select() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be retrieved.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_select() example

<?php 
  $db 
pg_connect('dbname=foo');
  
// This is safe somewhat, since all values are escaped.
  // However PostgreSQL supports JSON/Array. These are not
  // safe by neither escape nor prepared query.
  
$rec pg_select($db'post_log'$_POSTPG_DML_ESCAPE);
  if (
$rec) {
      echo 
"Records selected\n";
      
var_dump($rec);
  } else {
      echo 
"User must have sent wrong inputs\n";
  }
?>

Changelog

Version Description
7.1.0 The result_type parameter was added.
5.6.0 No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements



pg_send_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_send_executeSends a request to execute a prepared statement with given parameters, without waiting for the result(s)

Description

pg_send_execute ( resource $connection , string $stmtname , array $params ) : bool

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_execute()

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Prepare a query for execution
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_prepare($dbconn"my_query"'SELECT * FROM shops WHERE name = $1');
    
$res1 pg_get_result($dbconn);
  }

  
// Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_execute($dbconn"my_query", array("Joe's Widgets"));
    
$res2 pg_get_result($dbconn);
  }
  
  
// Execute the same prepared query, this time with a different parameter
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_execute($dbconn"my_query", array("Clothes Clothes Clothes"));
    
$res3 pg_get_result($dbconn);
  }
  
?>

See Also

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result



pg_send_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_send_prepareSends a request to create a prepared statement with the given parameters, without waiting for completion

Description

pg_send_prepare ( resource $connection , string $stmtname , string $query ) : bool

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Return Values

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_prepare()

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Prepare a query for execution
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_prepare($dbconn"my_query"'SELECT * FROM shops WHERE name = $1');
    
$res1 pg_get_result($dbconn);
  }

  
// Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_execute($dbconn"my_query", array("Joe's Widgets"));
    
$res2 pg_get_result($dbconn);
  }
  
  
// Execute the same prepared query, this time with a different parameter
  
if (!pg_connection_busy($dbconn)) {
    
pg_send_execute($dbconn"my_query", array("Clothes Clothes Clothes"));
    
$res3 pg_get_result($dbconn);
  }
  
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • pg_pconnect() - Open a persistent PostgreSQL connection
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
  • pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s)



pg_send_query_params

(PHP 5 >= 5.1.0, PHP 7)

pg_send_query_paramsSubmits a command and separate parameters to the server without waiting for the result(s)

Description

pg_send_query_params ( resource $connection , string $query , array $params ) : bool

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

Parameters

connection

PostgreSQL database connection resource.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example #1 Using pg_send_query_params()

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  
// Using parameters.  Note that it is not necessary to quote or escape
  // the parameter.
  
pg_send_query_params($dbconn'select count(*) from authors where city = $1', array('Perth'));
  
  
// Compare against basic pg_send_query usage
  
$str pg_escape_string('Perth');
  
pg_send_query($dbconn"select count(*) from authors where city = '${str}'");
?>

See Also



pg_send_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_send_query Sends asynchronous query

Description

pg_send_query ( resource $connection , string $query ) : bool

pg_send_query() sends a query or queries asynchronously to the connection. Unlike pg_query(), it can send multiple queries at once to PostgreSQL and get the results one by one using pg_get_result().

Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().

Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.

Parameters

connection

PostgreSQL database connection resource.

query

The SQL statement or statements to be executed.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

Examples

Example #1 pg_send_query() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from authors; select count(*) from authors;");
  }
  
  
$res1 pg_get_result($dbconn);
  echo 
"First call to pg_get_result(): $res1\n";
  
$rows1 pg_num_rows($res1);
  echo 
"$res1 has $rows1 records\n\n";
  
  
$res2 pg_get_result($dbconn);
  echo 
"Second call to pg_get_result(): $res2\n";
  
$rows2 pg_num_rows($res2);
  echo 
"$res2 has $rows2 records\n";
?>

The above example will output:

   First call to pg_get_result(): Resource id #3
   Resource id #3 has 3 records
   
   Second call to pg_get_result(): Resource id #4
   Resource id #4 has 1 records
   

See Also



pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_set_client_encoding Set the client encoding

Description

pg_set_client_encoding ([ resource $connection ], string $encoding ) : int

pg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.

PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.

Note:

The function used to be called pg_setclientencoding().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

encoding

The required client encoding. One of SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5 or WIN1250.

The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.

Return Values

Returns 0 on success or -1 on error.

Examples

Example #1 pg_set_client_encoding() example

<?php

$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
  echo 
"An error occurred.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn"UNICODE");

$result pg_query($conn"SELECT author, email FROM authors");
if (!
$result) {
  echo 
"An error occurred.\n";
  exit;
}

// Write out UTF-8 data
while ($row pg_fetch_row($result)) {
  echo 
"Author: $row[0]  E-mail: $row[1]";
  echo 
"<br />\n";
}
 
?>

See Also



pg_set_error_verbosity

(PHP 5 >= 5.1.0, PHP 7)

pg_set_error_verbosity Determines the verbosity of messages returned by pg_last_error() and pg_result_error()

Description

pg_set_error_verbosity ([ resource $connection ], int $verbosity ) : int

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Return Values

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Examples

Example #1 pg_set_error_verbosity() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");

  if (!
pg_connection_busy($dbconn)) {
      
pg_send_query($dbconn"select * from doesnotexist;");
  }
  
  
pg_set_error_verbosity($dbconnPGSQL_ERRORS_VERBOSE);
  
$res1 pg_get_result($dbconn);
  echo 
pg_result_error($res1);
?>

See Also



pg_socket

(PHP 5 >= 5.6.0, PHP 7)

pg_socket Get a read only handle to the socket underlying a PostgreSQL connection

Description

pg_socket ( resource $connection ) : resource

pg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

PostgreSQL database connection resource.

Return Values

A socket resource on success or FALSE on failure.



pg_trace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_traceEnable tracing a PostgreSQL connection

Description

pg_trace ( string $pathname [, string $mode = "w" [, resource $connection ]] ) : bool

pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.

For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the » PostgreSQL Documentation.

Parameters

pathname

The full path and file name of the file in which to write the trace log. Same as in fopen().

mode

An optional file access mode, same as for fopen().

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_trace() example

<?php
$pgsql_conn 
pg_connect("dbname=mark host=localhost");

if (
$pgsql_conn) {
   
pg_trace('/tmp/trace.log''w'$pgsql_conn);
   
pg_query("SELECT 1");
   
pg_untrace($pgsql_conn);
   
// Now /tmp/trace.log will contain backend communication
} else {
   print 
pg_last_error($pgsql_conn);
   exit;
}
?>

See Also



pg_transaction_status

(PHP 5 >= 5.1.0, PHP 7)

pg_transaction_statusReturns the current in-transaction status of the server

Description

pg_transaction_status ( resource $connection ) : int

Returns the current in-transaction status of the server.

Caution

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

Parameters

connection

PostgreSQL database connection resource.

Return Values

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

Examples

Example #1 pg_transaction_status() example

<?php
  $dbconn 
pg_connect("dbname=publisher") or die("Could not connect");
  
$stat pg_transaction_status($dbconn);
  if (
$stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 
'Connection is bad';
  } else if (
$stat === PGSQL_TRANSACTION_IDLE) {
      echo 
'Connection is currently idle';
  } else {
      echo 
'Connection is in a transaction state';
  }    
?>



pg_tty

(PHP 4, PHP 5, PHP 7)

pg_tty Return the TTY name associated with the connection

Description

pg_tty ([ resource $connection ] ) : string

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL connection resource.

Note:

pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the debug TTY of the connection, or FALSE on error.

Examples

Example #1 pg_tty() example

<?php
$pgsql_conn 
pg_connect("dbname=mark host=localhost");

if (
$pgsql_conn) {
   print 
"Server debug TTY is: " pg_tty($pgsql_conn) . "<br/>\n";
} else {
   print 
pg_last_error($pgsql_conn);
   exit;
}
?>



pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_unescape_bytea Unescape binary for bytea type

Description

pg_unescape_bytea ( string $data ) : string

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

Note:

When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parameters

data

A string containing PostgreSQL bytea data to be converted into a PHP binary string.

Return Values

A string containing the unescaped data.

Examples

Example #1 pg_unescape_bytea() example

<?php 
  
// Connect to the database
  
$dbconn pg_connect('dbname=foo');
  
  
// Get the bytea data
  
$res pg_query("SELECT data FROM gallery WHERE name='Pine trees'");  
  
$raw pg_fetch_result($res'data');
  
  
// Convert to binary and send to the browser
  
header('Content-type: image/jpeg');
  echo 
pg_unescape_bytea($raw);
?>

Changelog

Version Description
5.5.1 A warning is thrown if the input string is invalid.

See Also



pg_untrace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_untraceDisable tracing of a PostgreSQL connection

Description

pg_untrace ([ resource $connection ] ) : bool

Stop tracing started by pg_trace().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Always returns TRUE.

Examples

Example #1 pg_untrace() example

<?php
$pgsql_conn 
pg_connect("dbname=mark host=localhost");

if (
$pgsql_conn) {
   
pg_trace('/tmp/trace.log''w'$pgsql_conn);
   
pg_query("SELECT 1");
   
pg_untrace($pgsql_conn);
   
// Now tracing of backend communication is disabled
} else {
   print 
pg_last_error($pgsql_conn);
   exit;
}
?>

See Also

  • pg_trace() - Enable tracing a PostgreSQL connection



pg_update

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_update Update table

Description

pg_update ( resource $connection , string $table_name , array $data , array $condition [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

pg_update() updates records specified by assoc_array which has field=>value.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_update() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.

Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name, and whose values are what matched rows are to be updated to.

condition

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be updated.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_ESCAPE, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned. When PGSQL_DML_NO_CONV or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_update() example

<?php 
  $db 
pg_connect('dbname=foo');
  
$data = array('field1'=>'AA''field2'=>'BB');
  
// This is safe somewhat, since all values are escaped.
  // However PostgreSQL supports JSON/Array. These are not
  // safe by neither escape nor prepared query.
  
$res pg_update($db'post_log'$_POST$data);
  if (
$res) {
      echo 
"Data is updated: $res\n";
  } else {
      echo 
"User must have sent wrong inputs\n";
  }
?>

Changelog

Version Description
5.6.0 No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements



pg_version

(PHP 5, PHP 7)

pg_version Returns an array with client, protocol and server version (when available)

Description

pg_version ([ resource $connection ] ) : array

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns an array with client, protocol and server keys and values (if available). Returns FALSE on error or invalid connection.

Examples

Example #1 pg_version() example

<?php
  $dbconn 
pg_connect("host=localhost port=5432 dbname=mary")
     or die(
"Could not connect");
     
  
$v pg_version($dbconn);
  
  echo 
$v['client'];
?>

The above example will output:

   7.4
   

See Also


Table of Contents




SQLite


Introduction

This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.

SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.

Note:

For further information see the SQLite Website (» http://sqlite.org/).

Note: This extension offers support for SQLite 2.x. Sqlite 3.x is supported by the SQLite3 extension.



Installing/Configuring

Table of Contents


Requirements

The SQLite extension is enabled by default as of PHP 5.0. Beginning with PHP 5.4, the SQLite extension is available only via PECL.



Installation

Since PHP 5.0 this extension was bundled with PHP. Beginning with PHP 5.4, this extension is available only via PECL.

Windows users must enable php_sqlite.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:

extension=php_pdo.dll
   extension=php_sqlite.dll
On Linux or Unix operating systems, if you build PDO as a shared extension, you must build SQLite as a shared extension using the --with-sqlite=shared configure option.

The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.

SQLite 3 is supported through PDO SQLite.

Note: Windows installation for unprivileged accounts

On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:

SetEnv TMP c:/temp
If you are unable to establish this setting at the server level, you can implement the setting in your script:
<?php
putenv
('TMP=C:/temp');
?>
The setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite Configure Options
Name Default Changeable Changelog
sqlite.assoc_case "0" PHP_INI_ALL Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sqlite.assoc_case int

Whether to use mixed case (0), upper case (1) or lower case (2) hash indexes.

This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.

The SQLite library returns the column names in their natural case (that matches the case you used in your schema). When sqlite.assoc_case is set to 0 the natural case will be preserved. When it is set to 1 or 2, PHP will apply case folding on the hash keys to upper- or lower-case the keys, respectively.

Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.



Resource Types

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

SQLite result type constants
SQLITE_ASSOC (int)
Columns are returned into the array having the field name as the array index.
SQLITE_BOTH (int)
Columns are returned into the array having both a numerical index and the field name as the array index.
SQLITE_NUM (int)
Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

A number of functions may return status codes. The following constants are defined:

SQLite status code constants
SQLITE_OK (int)
Successful result.
SQLITE_ERROR (int)
SQL error or missing database.
SQLITE_INTERNAL (int)
An internal logic error in SQLite.
SQLITE_PERM (int)
Access permission denied.
SQLITE_ABORT (int)
Callback routine requested an abort.
SQLITE_BUSY (int)
The database file is locked.
SQLITE_LOCKED (int)
A table in the database is locked.
SQLITE_NOMEM (int)
Memory allocation failed.
SQLITE_READONLY (int)
Attempt to write a readonly database.
SQLITE_INTERRUPT (int)
Operation terminated internally.
SQLITE_IOERR (int)
Disk I/O error occurred.
SQLITE_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
SQLITE_NOTFOUND (int)
(Internal) Table or record not found.
SQLITE_FULL (int)
Insertion failed because database is full.
SQLITE_CANTOPEN (int)
Unable to open the database file.
SQLITE_PROTOCOL (int)
Database lock protocol error.
SQLITE_EMPTY (int)
(Internal) Database table is empty.
SQLITE_SCHEMA (int)
The database schema changed.
SQLITE_TOOBIG (int)
Too much data for one row of a table.
SQLITE_CONSTRAINT (int)
Abort due to constraint violation.
SQLITE_MISMATCH (int)
Data type mismatch.
SQLITE_MISUSE (int)
Library used incorrectly.
SQLITE_NOLFS (int)
Uses of OS features not supported on host.
SQLITE_AUTH (int)
Authorized failed.
SQLITE_ROW (int)
Internal process has another row ready.
SQLITE_DONE (int)
Internal process has finished executing.


SQLite Functions

Predefined Classes

SQLiteDatabase

Represents an opened SQLite database.

Constructor

Methods

  • query - Execute a query
  • queryExec - Execute a result-less query
  • arrayQuery - Execute a query and return the result as an array
  • singleQuery - Execute a query and return either an array for one single column or the value of the first row
  • unbufferedQuery - Execute an unbuffered query
  • lastInsertRowid - Returns the rowid of the most recently inserted row
  • changes - Returns the number of rows changed by the most recent statement
  • createAggregate - Register an aggregating UDF for use in SQL statements
  • createFunction - Register a UDF for use in SQL statements
  • busyTimeout - Sets or disables busy timeout duration
  • lastError - Returns the last error code of the most recently encountered error
  • fetchColumnTypes - Return an array of column types from a particular table

SQLiteResult

Represents a buffered SQLite result set.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • key - Return the current row index
  • next - Seek to the next row number
  • valid - Returns whether more rows are available
  • rewind - Seek to the first row number of the result set
  • prev - Seek to the previous row number of the result set
  • hasPrev - Returns whether or not a previous row is available
  • numRows - Returns the number of rows in the result set
  • seek - Seek to a particular row number

SQLiteUnbuffered

Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • next - Seek to the next row number
  • valid - Returns whether more rows are available

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_array_query -- SQLiteDatabase::arrayQueryExecute a query against a given database and returns an array

Description

sqlite_array_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
sqlite_array_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

public SQLiteDatabase::arrayQuery ( string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.

Tip

sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.

Parameters

query

The query to be executed.

Data inside the query should be properly escaped.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns an array of the entire result set; FALSE otherwise.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural style

<?php
$dbhandle 
sqlite_open('sqlitedb');
$result sqlite_array_query($dbhandle'SELECT name, email FROM users LIMIT 25'SQLITE_ASSOC);
foreach (
$result as $entry) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

Example #2 Object-oriented style

<?php
$dbhandle 
= new SQLiteDatabase('sqlitedb');
$result $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25'SQLITE_ASSOC);
foreach (
$result as $entry) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

See Also



sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase::busyTimeoutSet busy timeout duration, or disable busy handlers

Description

sqlite_busy_timeout ( resource $dbhandle , int $milliseconds ) : void

Object oriented style (method):

public SQLiteDatabase::busyTimeout ( int $milliseconds ) : void

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

milliseconds

The number of milliseconds. When set to 0, busy handlers will be disabled and SQLite will return immediately with a SQLITE_BUSY status code if another process/thread has the database locked for an update.

PHP sets the default busy timeout to be 60 seconds when the database is opened.

Note:

There are one thousand (1000) milliseconds in one second.

Return Values

No value is returned.

Examples

Example #1 Procedural style

<?php
$dbhandle 
sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle0); // disable busy handler
?>

Example #2 Object oriented style

<?php
$dbhandle 
= new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist



sqlite_changes

SQLiteDatabase::changes

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_changes -- SQLiteDatabase::changes Returns the number of rows that were changed by the most recent SQL statement

Description

sqlite_changes ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::changes ( void ) : int

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of changed rows.

Examples

Example #1 Procedural style

<?php
$dbhandle 
sqlite_open('mysqlitedb');
$query sqlite_query($dbhandle"UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!
$query) {
    exit(
'Error in query.');
} else {
    echo 
'Number of rows modified: 'sqlite_changes($dbhandle);
}
?>

Example #2 Object oriented style

<?php
$dbhandle 
= new SQLiteDatabase('mysqlitedb');
$query $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!
$query) {
    exit(
'Error in query.');
} else {
    echo 
'Number of rows modified: '$dbhandle->changes();
}
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist



sqlite_close

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_closeCloses an open SQLite database

Description

sqlite_close ( resource $dbhandle ) : void

Closes the given db_handle database handle. If the database was persistent, it will be closed and removed from the persistent list.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Return Values

No value is returned.

Examples

Example #1 sqlite_close() example

<?php
$dbhandle 
sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist



sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult::column -- SQLiteUnbuffered::columnFetches a column from the current row of a result set

Description

sqlite_column ( resource $result , mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed
SQLiteResult::column ( mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed
SQLiteUnbuffered::column ( mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed

Fetches the value of a column named index_or_name (if it is a string), or of the ordinal column numbered index_or_name (if it is an integer) from the current row of the query result handle result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

index_or_name

The column index or name to fetch.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the column value.

Notes

Note:

Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

See Also



sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase::createAggregateRegister an aggregating UDF for use in SQL statements

Description

sqlite_create_aggregate ( resource $dbhandle , string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] ) : void

Object oriented style (method):

public SQLiteDatabase::createAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] ) : void

sqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Function parameters are &$context, $value, ....

finalize_func

Callback function to aggregate the "stepped" data from each row. Function parameter is &$context and the function should return the final result of aggregation.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

No value is returned.

Examples

Example #1 max_length aggregation function example

<?php
$data 
= array(
   
'one',
   
'two',
   
'three',
   
'four',
   
'five',
   
'six',
   
'seven',
   
'eight',
   
'nine',
   
'ten',
   );
$dbhandle sqlite_open(':memory:');
sqlite_query($dbhandle"CREATE TABLE strings(a)");
foreach (
$data as $str) {
    
$str sqlite_escape_string($str);
    
sqlite_query($dbhandle"INSERT INTO strings VALUES ('$str')");
}

function 
max_len_step(&$context$string
{
    if (
strlen($string) > $context) {
        
$context strlen($string);
    }
}

function 
max_len_finalize(&$context
{
    return 
$context;
}

sqlite_create_aggregate($dbhandle'max_len''max_len_step''max_len_finalize');

var_dump(sqlite_array_query($dbhandle'SELECT max_len(a) from strings'));

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Note:

The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also



sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5 < 5.4.0, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction Registers a "regular" User Defined Function for use in SQL statements

Description

sqlite_create_function ( resource $dbhandle , string $function_name , callable $callback [, int $num_args = -1 ] ) : void

Object oriented style (method):

public SQLiteDatabase::createFunction ( string $function_name , callable $callback [, int $num_args = -1 ] ) : void

sqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

No value is returned.

Examples

Example #1 sqlite_create_function() example

<?php
function md5_and_reverse($string
{
    return 
strrev(md5($string));
}

if (
$dbhandle sqlite_open('mysqlitedb'0666$sqliteerror)) {
    
    
sqlite_create_function($dbhandle'md5rev''md5_and_reverse'1);
    
    
$sql  'SELECT md5rev(filename) FROM files';
    
$rows sqlite_array_query($dbhandle$sql);
} else {
    echo 
'Error opening sqlite db: ' $sqliteerror;
    exit;
}
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

PHP registers a special function named php when the database is first opened. The php function can be used to call any PHP function without having to register it first.

Example #2 Example of using the PHP function

<?php
$rows 
sqlite_array_query($dbhandle"SELECT php('md5', filename) from files");
?>

This example will call the md5() on each filename column in the database and return the result into $rows

Note:

For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.

Tip

It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.

Tip

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also



sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::currentFetches the current row from a result set as an array

Description

sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

See Also



sqlite_error_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_error_stringReturns the textual description of an error code

Description

sqlite_error_string ( int $error_code ) : string

Returns a human readable description of the error_code returned from sqlite_last_error().

Parameters

error_code

The error code being used, which might be passed in from sqlite_last_error().

Return Values

Returns a human readable description of the error_code, as a string.

See Also



sqlite_escape_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_escape_stringEscapes a string for use as a query parameter

Description

sqlite_escape_string ( string $item ) : string

sqlite_escape_string() will correctly quote the string specified by item for use in an SQLite SQL statement. This includes doubling up single-quote characters (') and checking for binary-unsafe characters in the query string.

Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data. In practice, this shouldn't be a problem, as your schema should be such that you don't use such things on binary columns (in fact, it might be better to store binary data using other means, such as in files).

Parameters

item

The string being quoted.

If the item contains a NUL character, or if it begins with a character whose ordinal value is 0x01, PHP will apply a binary encoding scheme so that you can safely store and retrieve binary data.

Return Values

Returns an escaped string for use in an SQLite SQL statement.

Notes

Note: Do not use this function to encode the return values from UDF's created using sqlite_create_function() or sqlite_create_aggregate() - use sqlite_udf_encode_binary() instead.

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

See Also



sqlite_exec

SQLiteDatabase::exec

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.3)

sqlite_exec -- SQLiteDatabase::execExecutes a result-less query against a given database

Description

sqlite_exec ( resource $dbhandle , string $query [, string &$error_msg ] ) : bool
sqlite_exec ( string $query , resource $dbhandle ) : bool

Object oriented style (method):

public SQLiteDatabase::queryExec ( string $query [, string &$error_msg ] ) : bool

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version Description
5.1.0 Added the error_msg parameter

Examples

Example #1 Procedural example

<?php
$dbhandle 
sqlite_open('mysqlitedb');
$query sqlite_exec($dbhandle"UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'"$error);
if (!
$query) {
    exit(
"Error in query: '$error'");
} else {
    echo 
'Number of rows modified: 'sqlite_changes($dbhandle);
}
?>

Example #2 Object-oriented example

<?php
$dbhandle 
= new SQLiteDatabase('mysqlitedb');
$query $dbhandle->queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'"$error);
if (!
$query) {
    exit(
"Error in query: '$error'");
} else {
    echo 
'Number of rows modified: '$dbhandle->changes();
}
?>

See Also



sqlite_factory

(PHP 5 < 5.4.0)

sqlite_factoryOpens an SQLite database and returns an SQLiteDatabase object

Description

sqlite_factory ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : SQLiteDatabase

sqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.

Parameters

filename

The filename of the SQLite database.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns an SQLiteDatabase object on success, NULL on error.

Examples

Example #1 sqlite_factory() example

<?php
$dbhandle 
sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist



sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAllFetches all rows from a result set as an array of arrays

Description

sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_fetch_all() returns an array of the entire result set from the result resource. It is similar to calling sqlite_query() (or sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle 
sqlite_open('sqlitedb');
$query sqlite_query($dbhandle'SELECT name, email FROM users LIMIT 25');
$result sqlite_fetch_all($querySQLITE_ASSOC);
foreach (
$result as $entry) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle 
= new SQLiteDatabase('sqlitedb');

$query $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result $query->fetchAll(SQLITE_ASSOC);
foreach (
$result as $entry) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

See Also



sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetchFetches the next row from a result set as an array

Description

sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Fetches the next row from the given result handle. If there are no more rows, returns FALSE, otherwise returns an associative array representing the row data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle 
sqlite_open('sqlitedb');
$query sqlite_query($dbhandle'SELECT name, email FROM users LIMIT 25');
while (
$entry sqlite_fetch_array($querySQLITE_ASSOC)) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle 
= new SQLiteDatabase('sqlitedb');

$query $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry $query->fetch(SQLITE_ASSOC)) {
    echo 
'Name: ' $entry['name'] . '  E-mail: ' $entry['email'];
}
?>

See Also



sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5 < 5.4.0)

sqlite_fetch_column_types -- SQLiteDatabase::fetchColumnTypes Return an array of column types from a particular table

Description

sqlite_fetch_column_types ( string $table_name , resource $dbhandle [, int $result_type = SQLITE_ASSOC ] ) : array

Object oriented style (method):

public SQLiteDatabase::fetchColumnTypes ( string $table_name [, int $result_type = SQLITE_ASSOC ] ) : array

sqlite_fetch_column_types() returns an array of column data types from the specified table_name table.

Parameters

table_name

The table name to query.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_ASSOC is the default for this function.

Return Values

Returns an array of column data types; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version Description
5.1.0 Added result_type

Examples

Example #1 Procedural example

<?php
$db 
sqlite_open('mysqlitedb');
sqlite_query($db'CREATE TABLE foo (bar varchar(10), arf text)');
$cols sqlite_fetch_column_types('foo'$dbSQLITE_ASSOC);

foreach (
$cols as $column => $type) {
    echo 
"Column: $column  Type: $type\n";
}
?>

Example #2 Object-oriented example

<?php
$db 
= new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols $db->fetchColumnTypes('foo'SQLITE_ASSOC);

foreach (
$cols as $column => $type) {
    echo 
"Column: $column  Type: $type\n";
}
?>

The above example will output:

   Column: bar  Type: VARCHAR
   Column: arf  Type: TEXT
   



sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5 < 5.4.0)

sqlite_fetch_object -- SQLiteResult::fetchObject -- SQLiteUnbuffered::fetchObjectFetches the next row from a result set as an object

Description

sqlite_fetch_object ( resource $result [, string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object

Object oriented style (method):

SQLiteResult::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object
SQLiteUnbuffered::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object
Warning

This function is currently not documented; only its argument list is available.



sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingleFetches the first column of a result set as a string

Description

sqlite_fetch_single ( resource $result [, bool $decode_binary = TRUE ] ) : string

Object oriented style (method):

SQLiteResult::fetchSingle ([ bool $decode_binary = TRUE ] ) : string
SQLiteUnbuffered::fetchSingle ([ bool $decode_binary = TRUE ] ) : string

sqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.

This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the first column value, as a string.

Examples

Example #1 A sqlite_fetch_single() example

<?php
if ($dbhandle sqlite_open('mysqlitedb'0666$sqliteerror)) {

    
$sql "SELECT id FROM sometable WHERE id = 42";
    
$res sqlite_query($dbhandle$sql);

    if (
sqlite_num_rows($res) > 0) {
        echo 
sqlite_fetch_single($res); // 42
    
}
    
    
sqlite_close($dbhandle);
}
?>

See Also



sqlite_fetch_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_stringAlias of sqlite_fetch_single()

Description

This function is an alias of: sqlite_fetch_single().



sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldNameReturns the name of a particular field

Description

sqlite_field_name ( resource $result , int $field_index ) : string

Object oriented style (method):

SQLiteResult::fieldName ( int $field_index ) : string
SQLiteUnbuffered::fieldName ( int $field_index ) : string

Given the ordinal column number, field_index, sqlite_field_name() returns the name of that field in the result set result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

field_index

The ordinal column number in the result set.

Return Values

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.



sqlite_has_more

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_has_moreFinds whether or not more rows are available

Description

sqlite_has_more ( resource $result ) : bool

Finds whether more rows are available from the given result set.

Parameters

result

The SQLite result resource.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement



sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5 < 5.4.0)

sqlite_has_prev -- SQLiteResult::hasPrevReturns whether or not a previous row is available

Description

sqlite_has_prev ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::hasPrev ( void ) : bool

Find whether there are more previous rows from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

See Also



sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0 < 5.4.0)

sqlite_key -- SQLiteResult::keyReturns the current row index

Description

Object oriented style (method):

SQLiteResult::key ( void ) : int

SQLiteResult::key() returns the current row index of the buffered result set result.

Unlike all other SQLite functions, this function does not have a procedural version, and can only be called as a method on a SQLiteResult object.

Return Values

Returns the current row index of the buffered result set result.

See Also



sqlite_last_error

SQLiteDatabase::lastError

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase::lastErrorReturns the error code of the last error for a database

Description

sqlite_last_error ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::lastError ( void ) : int

Returns the error code from the last operation performed on dbhandle (the database handle), or 0 when no error occurred. A human readable description of the error code can be retrieved using sqlite_error_string().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns an error code, or 0 if no error occurred.

See Also



sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowidReturns the rowid of the most recently inserted row

Description

sqlite_last_insert_rowid ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::lastInsertRowid ( void ) : int

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

Tip

You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the row id, as an integer.



sqlite_libencoding

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libencodingReturns the encoding of the linked SQLite library

Description

sqlite_libencoding ( void ) : string

The SQLite library may be compiled in either ISO-8859-1 or UTF-8 compatible modes. This function allows you to determine which encoding scheme is used by your version of the library.

Warning

The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode. However, this is a misnomer; rather than handling ISO-8859-1, it operates according to your current locale settings for string comparisons and sort ordering. So, rather than ISO-8859-1, you should think of it as being '8-bit' instead.

When compiled with UTF-8 support, sqlite handles encoding and decoding of UTF-8 multi-byte character sequences, but does not yet do a complete job when working with the data (no normalization is performed for example), and some comparison operations may still not be carried out correctly.

Warning

It is not recommended that you use PHP in a web-server configuration with a version of the SQLite library compiled with UTF-8 support, since libsqlite will abort the process if it detects a problem with the UTF-8 encoding.

Return Values

Returns the library encoding.

See Also



sqlite_libversion

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libversionReturns the version of the linked SQLite library

Description

sqlite_libversion ( void ) : string

Returns the version of the linked SQLite library.

Return Values

Returns the library version, as a string.

See Also



sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::nextSeek to the next row number

Description

sqlite_next ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::next ( void ) : bool
SQLiteUnbuffered::next ( void ) : bool

sqlite_next() advances the result handle result to the next row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns TRUE on success, or FALSE if there are no more rows.

See Also



sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFieldsReturns the number of fields in a result set

Description

sqlite_num_fields ( resource $result ) : int

Object oriented style (method):

SQLiteResult::numFields ( void ) : int
SQLiteUnbuffered::numFields ( void ) : int

Returns the number of fields in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of fields, as an integer.

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_num_rows() - Returns the number of rows in a buffered result set



sqlite_num_rows

SQLiteResult::numRows

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult::numRowsReturns the number of rows in a buffered result set

Description

sqlite_num_rows ( resource $result ) : int

Object oriented style (method):

SQLiteResult::numRows ( void ) : int

Returns the number of rows in the buffered result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 Procedural example

<?php
$db 
sqlite_open('mysqlitedb');
$result sqlite_query($db"SELECT * FROM mytable WHERE name='John Doe'");
$rows sqlite_num_rows($result);

echo 
"Number of rows: $rows";
?>

Example #2 Object-oriented example

<?php
$db 
= new SQLiteDatabase('mysqlitedb');
$result $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows $result->numRows();

echo 
"Number of rows: $rows";
?>

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_num_fields() - Returns the number of fields in a result set



sqlite_open

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_openOpens an SQLite database and create the database if it does not exist

Description

sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : resource

Object oriented style (constructor):

final public SQLiteDatabase::__construct ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens an SQLite database or creates the database if it does not exist.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

Examples

Example #1 sqlite_open() example

<?php
if ($db sqlite_open('mysqlitedb'0666$sqliteerror)) { 
    
sqlite_query($db'CREATE TABLE foo (bar varchar(10))');
    
sqlite_query($db"INSERT INTO foo VALUES ('fnord')");
    
$result sqlite_query($db'select bar from foo');
    
var_dump(sqlite_fetch_array($result)); 
} else {
    die(
$sqliteerror);
}
?>

Notes

Tip

On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you do have such a script, it is recommended that you close the handle prior to forking and then re-open it in the child and/or parent. For more information on this issue, see » The C language interface to the SQLite library in the section entitled Multi-Threading And SQLite.

Tip

It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.

Note: Starting with SQLite library version 2.8.2, you can specify :memory: as the filename to create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with the ATTACH DATABASE SQL statement to load other databases and move and query data between them.

Note: SQLite is safe mode and open_basedir aware.

See Also

  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object



sqlite_popen

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_popen Opens a persistent handle to an SQLite database and create the database if it does not exist

Description

sqlite_popen ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : resource

This function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.

sqlite_popen() will first check to see if a persistent handle has already been opened for the given filename. If it finds one, it returns that handle to your script, otherwise it opens a fresh handle to the database.

The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).

Note: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled. To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object



sqlite_prev

SQLiteResult::prev

(PHP 5 < 5.4.0)

sqlite_prev -- SQLiteResult::prevSeek to the previous row number of a result set

Description

sqlite_prev ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::prev ( void ) : bool

sqlite_prev() seeks back the result handle to the previous row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE on success, or FALSE if there are no more previous rows.

See Also



sqlite_query

SQLiteDatabase::query

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_query -- SQLiteDatabase::queryExecutes a query against a given database and returns a result handle

Description

sqlite_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource
sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource

Object oriented style (method):

public SQLiteDatabase::query ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : SQLiteResult

Executes an SQL statement given by the query against a given database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a result handle or FALSE on failure. For queries that return rows, the result handle can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

Regardless of the query type, this function will return FALSE if the query failed.

sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.

Changelog

Version Description
5.1.0 Added the error_msg parameter

Notes

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.

When executing multiple queries, the return value of this function will be FALSE if there was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

See Also



sqlite_rewind

SQLiteResult::rewind

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult::rewindSeek to the first row number

Description

sqlite_rewind ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::rewind ( void ) : bool

sqlite_rewind() seeks back to the first row in the given result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if there are no rows in the result set, TRUE otherwise.

See Also



sqlite_seek

SQLiteResult::seek

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_seek -- SQLiteResult::seekSeek to a particular row number of a buffered result set

Description

sqlite_seek ( resource $result , int $rownum ) : bool

Object oriented style (method):

SQLiteResult::seek ( int $rownum ) : bool

sqlite_seek() seeks to the row given by the parameter rownum.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if the row does not exist, TRUE otherwise.

See Also



sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_single_query -- SQLiteDatabase::singleQuery Executes a query and returns either an array for one single column or the value of the first row

Description

sqlite_single_query ( resource $db , string $query [, bool $first_row_only [, bool $decode_binary ]] ) : array

Object oriented style (method):

public SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] ) : array
Warning

This function is currently not documented; only its argument list is available.



sqlite_udf_decode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binaryDecode binary data passed as parameters to an UDF

Description

sqlite_udf_decode_binary ( string $data ) : string

Decodes binary data passed as parameters to a UDF.

You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Parameters

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Return Values

The decoded string.

Examples

Example #1 binary-safe max_length aggregation function example

<?php
$data 
= array(
   
'one',
   
'two',
   
'three',
   
'four',
   
'five',
   
'six',
   
'seven',
   
'eight',
   
'nine',
   
'ten',
   );
$db sqlite_open(':memory:');
sqlite_query($db"CREATE TABLE strings(a)");
foreach (
$data as $str) {
    
$str sqlite_escape_string($str);
    
sqlite_query($db"INSERT INTO strings VALUES ('$str')");
}

function 
max_len_step(&$context$string
{
    
$string sqlite_udf_decode_binary($string);
    if (
strlen($string) > $context) {
        
$context strlen($string);
    }
}

function 
max_len_finalize(&$context
{
    return 
$context;
}

sqlite_create_aggregate($db'max_len''max_len_step''max_len_finalize');

var_dump(sqlite_array_query($db'SELECT max_len(a) from strings'));

?>

See Also



sqlite_udf_encode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_encode_binaryEncode binary data before returning it from an UDF

Description

sqlite_udf_encode_binary ( string $data ) : string

sqlite_udf_encode_binary() applies a binary encoding to the data so that it can be safely returned from queries (since the underlying libsqlite API is not binary safe).

If there is a chance that your data might be binary unsafe (e.g.: it contains a NUL byte in the middle rather than at the end, or if it has and 0x01 byte as the first character) then you must call this function to encode the return value from your UDF.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Note:

Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!

Parameters

data

The string being encoded.

Return Values

The encoded string.

See Also



sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- SQLiteDatabase::unbufferedQueryExecute a query that does not prefetch and buffer all data

Description

sqlite_unbuffered_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource
sqlite_unbuffered_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource

Object oriented style (method):

public SQLiteDatabase::unbufferedQuery ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : SQLiteUnbuffered

sqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.

This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.

Note:

Functions such as sqlite_seek(), sqlite_rewind(), sqlite_next(), sqlite_current(), and sqlite_num_rows() do not work on result handles returned from sqlite_unbuffered_query().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns a result handle or FALSE on failure.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

Changelog

Version Description
5.1.0 Added the error_msg parameter

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle



sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5 < 5.4.0)

sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::validReturns whether more rows are available

Description

sqlite_valid ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::valid ( void ) : bool
SQLiteUnbuffered::valid ( void ) : bool

Finds whether more rows are available from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement


Table of Contents




SQLite3


Introduction

Support for SQLite version 3 databases.



Installing/Configuring

Table of Contents


Requirements

As of PHP 7.4.0 » libsqlite ≥ 3.7.4 is required. Formerly, the bundled libsqlite could have been used instead.



Installation

The SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time.

Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.

Note: Additional setup on Windows as of PHP 7.4.0

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsqlite3.dll.

Note:

This extension was briefly a PECL extension but that version is only recommended for experimental use.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite3 Configure Options
Name Default Changeable Changelog
sqlite3.extension_dir "" PHP_INI_SYSTEM Available as of PHP 5.3.11.
sqlite3.defensive 1 PHP_INI_SYSTEM Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0.

Here's a short explanation of the configuration directives.

sqlite3.extension_dir string

Path to the directory where the loadable extensions for SQLite reside.

sqlite3.defensive bool

When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. This forbids writing directly to the schema, shadow tables (eg. FTS data tables), or the sqlite_dbpage virtual table. This php.ini setting is only effective for libsqlite ≥ 3.26.0.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SQLITE3_ASSOC (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column name as returned in the corresponding result set.
SQLITE3_NUM (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column number as returned in the corresponding result set, starting at column 0.
SQLITE3_BOTH (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
SQLITE3_INTEGER (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not already exist.
SQLITE3_DETERMINISTIC (integer)
Specifies that a function created with SQLite3::createFunction() is deterministic, i.e. it always returns the same result given the same inputs within a single SQL statement. (Available as of PHP 7.1.4.)



The SQLite3 class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

A class that interfaces SQLite 3 databases.

Class synopsis

SQLite3 {
/* Methods */
public backup ( SQLite3 $destination_db [, string $source_dbname = "main" [, string $destination_dbname = "main" ]] ) : bool
public busyTimeout ( int $msecs ) : bool
public changes ( void ) : int
public close ( void ) : bool
public __construct ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] )
public createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] ) : bool
public createCollation ( string $name , callable $callback ) : bool
public createFunction ( string $name , mixed $callback [, int $argument_count = -1 [, int $flags = 0 ]] ) : bool
enableExceptions ([ bool $enableExceptions = FALSE ] ) : bool
public static escapeString ( string $value ) : string
public exec ( string $query ) : bool
public lastErrorCode ( void ) : int
public lastErrorMsg ( void ) : string
public lastInsertRowID ( void ) : int
public loadExtension ( string $shared_library ) : bool
public open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] ) : void
public openBlob ( string $table , string $column , int $rowid [, string $dbname = "main" [, int $flags = SQLITE3_OPEN_READONLY ]] ) : resource
public prepare ( string $query ) : SQLite3Stmt
public query ( string $query ) : SQLite3Result
public querySingle ( string $query [, bool $entire_row = FALSE ] ) : mixed
public static version ( void ) : array
}

SQLite3::backup

(PHP 7 >= 7.4.0)

SQLite3::backupBackup one database to another database

Description

public SQLite3::backup ( SQLite3 $destination_db [, string $source_dbname = "main" [, string $destination_dbname = "main" ]] ) : bool

SQLite3::backup() copies the contents of one database into another, overwriting the contents of the destination database. It is useful either for creating backups of databases or for copying in-memory databases to or from persistent files.

Parameters

destination_db

A database connection opened with SQLite3::open().

source_dbname

The database name is "main" for the main database, "temp" for the temporary database, or the name specified after the AS keyword in an ATTACH statement for an attached database.

destination_dbname

Analogous to source_dbname but for the destination_db.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Backup an existing database

<?php
// $conn is a connection to an already opened sqlite3 database

$backup = new SQLite3('backup.sqlite');
$conn->backup($backup);
?>


SQLite3::busyTimeout

(PHP 5 >= 5.3.3, PHP 7)

SQLite3::busyTimeoutSets the busy connection handler

Description

public SQLite3::busyTimeout ( int $msecs ) : bool

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

Parameters

msecs

The milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.

Return Values

Returns TRUE on success, or FALSE on failure.



SQLite3::changes

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::changes Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

Description

public SQLite3::changes ( void ) : int

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

Parameters

This function has no parameters.

Return Values

Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

Examples

Example #1 SQLite3::changes() example

<?php
$db 
= new SQLite3('mysqlitedb.db');

$query $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if (
$query) {
    echo 
'Number of rows modified: '$db->changes();
}
?>



SQLite3::close

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::closeCloses the database connection

Description

public SQLite3::close ( void ) : bool

Closes the database connection.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SQLite3::close() example

<?php
$db 
= new SQLite3('mysqlitedb.db');
$db->close();
?>



SQLite3::__construct

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::__construct Instantiates an SQLite3 object and opens an SQLite 3 database

Description

public SQLite3::__construct ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] )

Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database, or :memory: to use in-memory database. If filename is an empty string, then a private, temporary on-disk database will be created. This private database will be automatically deleted as soon as the database connection is closed.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.

Return Values

Returns an SQLite3 object on success.

Errors/Exceptions

Throws an Exception on failure.

Changelog

Version Description
7.0.10 The filename can now be empty to use a private, temporary on-disk database.

Examples

Example #1 SQLite3::__construct() example

<?php
$db 
= new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar TEXT)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>



SQLite3::createAggregate

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createAggregateRegisters a PHP function for use as an SQL aggregate function

Description

public SQLite3::createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] ) : bool

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

Parameters

name

Name of the SQL aggregate to be created or redefined.

step_callback

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as:

step ( mixed $context , int $rownumber , mixed $value1 [, mixed $... ] ) : mixed
context

NULL for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber

The current row number.

value1

The first argument passed to the aggregate.

...

Further arguments passed to the aggregate.

The return value of this function will be used as the context argument in the next call of the step or finalize functions.

final_callback

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini ( mixed $context , int $rownumber ) : mixed
context

Holds the return value from the very last call to the step function.

rownumber

Always 0.

The return value of this function will be used as the return value for the aggregate.

argument_count

The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

Return Values

Returns TRUE upon successful creation of the aggregate, or FALSE on failure.

Examples

Example #1 max_length aggregation function example

<?php
$data 
= array(
   
'one',
   
'two',
   
'three',
   
'four',
   
'five',
   
'six',
   
'seven',
   
'eight',
   
'nine',
   
'ten',
   );
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE strings(a)");
$insert $db->prepare('INSERT INTO strings VALUES (?)');
foreach (
$data as $str) {
    
$insert->bindValue(1$str);
    
$insert->execute();
}
$insert null;

function 
max_len_step($context$rownumber$string)
{
    if (
strlen($string) > $context) {
        
$context strlen($string);
    }
    return 
$context;
}

function 
max_len_finalize($context$rownumber)
{
    return 
$context === null $context;
}

$db->createAggregate('max_len''max_len_step''max_len_finalize');

var_dump($db->querySingle('SELECT max_len(a) from strings'));
?>

The above example will output:

   int(5)
   

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a $context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the $string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the $context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use SQLite3::createAggregate() to override SQLite native SQL functions.



SQLite3::createCollation

(PHP 5 >= 5.3.11, PHP 7)

SQLite3::createCollationRegisters a PHP function for use as an SQL collating function

Description

public SQLite3::createCollation ( string $name , callable $callback ) : bool

Registers a PHP function or user-defined function for use as a collating function within SQL statements.

Parameters

name

Name of the SQL collating function to be created or redefined

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two values and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

This function need to be defined as:

collation ( mixed $value1 , mixed $value2 ) : int

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SQLite3::createCollation() example

Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.

<?php

$db 
= new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->createCollation('NATURAL_CMP''strnatcmp');

$defaultSort $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");

echo 
"default:\n";
while (
$row $defaultSort->fetchArray()){
    echo 
$row['col1'], "\n";
}

echo 
"\nnatural:\n";
while (
$row $naturalSort->fetchArray()){
    echo 
$row['col1'], "\n";
}

$db->close();

?>

The above example will output:

   
   default:
   a1
   a10
   a2
   
   natural:
   a1
   a2
   a10
   
   

See Also



SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createFunctionRegisters a PHP function for use as an SQL scalar function

Description

public SQLite3::createFunction ( string $name , mixed $callback [, int $argument_count = -1 [, int $flags = 0 ]] ) : bool

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

Parameters

name

Name of the SQL function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

This function need to be defined as:

callback ( mixed $value1 [, mixed $... ] ) : mixed
value1

The first argument passed to the SQL function.

...

Further arguments passed to the SQL function.

argument_count

The number of arguments that the SQL function takes. If this parameter is -1, then the SQL function may take any number of arguments.

flags

A bitwise conjunction of flags. Currently, only SQLITE3_DETERMINISTIC is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

Return Values

Returns TRUE upon successful creation of the function, FALSE on failure.

Changelog

Version Description
7.1.4 The flags parameter has been added.

Examples

Example #1 SQLite3::createFunction() example

<?php
function my_udf_md5($string) {
    return 
md5($string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5''my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

The above example will output something similar to:

   string(32) "098f6bcd4621d373cade4e832627b4f6"
   



SQLite3::enableExceptions

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::enableExceptions Enable throwing exceptions

Description

SQLite3::enableExceptions ([ bool $enableExceptions = FALSE ] ) : bool

Controls whether the SQLite3 instance will throw exceptions or warnings on error.

Parameters

enable

When TRUE, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will throw exceptions on error.

When FALSE, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will raise warnings on error.

For either mode, the error code and message, if any, will be available via SQLite3::lastErrorCode() and SQLite3::lastErrorMsg() respectively.

Return Values

Returns the old value; TRUE if exceptions were enabled, FALSE otherwise.

Examples

Example #1 SQLite3::enableExceptions() example

<?php
$sqlite 
= new SQLite3(':memory:');
try {
    
$sqlite->exec('create table foo');
    
$sqlite->enableExceptions(true);
    
$sqlite->exec('create table bar');
} catch (
Exception $e) {
    echo 
'Caught exception: ' $e->getMessage();
}
?>

The above example will output something similar to:

   Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4
   Caught exception: near "bar": syntax error
   


SQLite3::escapeString

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::escapeStringReturns a string that has been properly escaped

Description

public static SQLite3::escapeString ( string $value ) : string

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Warning

This function is not (yet) binary safe!

To properly handle BLOB fields which may contain NUL characters, use SQLite3Stmt::bindParam() instead.

Parameters

value

The string to be escaped.

Return Values

Returns a properly escaped string that may be used safely in an SQL statement.

Notes

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.



SQLite3::exec

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::execExecutes a result-less query against a given database

Description

public SQLite3::exec ( string $query ) : bool

Executes a result-less query against a given database.

Note: SQLite3 may need to create » temporary files during the execution of queries, so the respective directories may have to be writable.

Parameters

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

Return Values

Returns TRUE if the query succeeded, FALSE on failure.

Examples

Example #1 SQLite3::exec() example

<?php
$db 
= new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE bar (bar STRING)');
?>



SQLite3::lastErrorCode

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastErrorCode Returns the numeric result code of the most recent failed SQLite request

Description

public SQLite3::lastErrorCode ( void ) : int

Returns the numeric result code of the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an integer value representing the numeric result code of the most recent failed SQLite request.



SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastErrorMsg Returns English text describing the most recent failed SQLite request

Description

public SQLite3::lastErrorMsg ( void ) : string

Returns English text describing the most recent failed SQLite request.

Parameters

This function has no parameters.

Return Values

Returns an English string describing the most recent failed SQLite request.



SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastInsertRowIDReturns the row ID of the most recent INSERT into the database

Description

public SQLite3::lastInsertRowID ( void ) : int

Returns the row ID of the most recent INSERT into the database.

Parameters

This function has no parameters.

Return Values

Returns the row ID of the most recent INSERT into the database



SQLite3::loadExtension

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::loadExtensionAttempts to load an SQLite extension library

Description

public SQLite3::loadExtension ( string $shared_library ) : bool

Attempts to load an SQLite extension library.

Parameters

shared_library

The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

Return Values

Returns TRUE if the extension is successfully loaded, FALSE on failure.

Examples

Example #1 SQLite3::loadExtension() example

<?php
$db 
= new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>



SQLite3::open

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::openOpens an SQLite database

Description

public SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] ) : void

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

Parameters

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.

Return Values

No value is returned.

Examples

Example #1 SQLite3::open() example

<?php
/**
 * Simple example of extending the SQLite3 class and changing the __construct
 * parameters, then using the open method to initialize the DB.
 */
class MyDB extends SQLite3
{
    function 
__construct()
    {
        
$this->open('mysqlitedb.db');
    }
}

$db = new MyDB();

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>



SQLite3::openBlob

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::openBlobOpens a stream resource to read a BLOB

Description

public SQLite3::openBlob ( string $table , string $column , int $rowid [, string $dbname = "main" [, int $flags = SQLITE3_OPEN_READONLY ]] ) : resource

Opens a stream resource to read or write a BLOB, which would be selected by:

SELECT column FROM dbname.table WHERE rowid = rowid

Note: It is not possible to change the size of a BLOB by writing to the stream. Instead, an UPDATE statement has to be executed, possibly using SQLite's zeroblob() function to set the desired BLOB size.

Parameters

table

The table name.

column

The column name.

rowid

The row ID.

dbname

The symbolic name of the DB

flags

Either SQLITE3_OPEN_READONLY or SQLITE3_OPEN_READWRITE to open the stream for reading only, or for reading and writing, respectively.

Return Values

Returns a stream resource, or FALSE on failure.

Changelog

Version Description
7.2.0 The flags parameter has been added, allowing to write BLOBs; formerly only reading was supported.

Examples

Example #1 SQLite3::openBlob() example

<?php
$conn 
= new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES ('Lorem ipsum')");
$stream $conn->openBlob('test''text'1);
echo 
stream_get_contents($stream);
fclose($stream); // mandatory, otherwise the next line would fail
$conn->close();
?>

The above example will output:

   Lorem ipsum
   

Example #2 Incrementally writing a BLOB

<?php
$conn 
= new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES (zeroblob(36))");
$stream $conn->openBlob('test''text'1'main'SQLITE3_OPEN_READWRITE);
for (
$i 0$i 3$i++) {
    
fwrite($stream,  "Lorem ipsum\n");
}
fclose($stream);
echo 
$conn->querySingle("SELECT text FROM test");
$conn->close();
?>

The above example will output:

   Lorem ipsum
   Lorem ipsum
   Lorem ipsum
   



SQLite3::prepare

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::preparePrepares an SQL statement for execution

Description

public SQLite3::prepare ( string $query ) : SQLite3Stmt

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

Parameters

query

The SQL query to prepare.

Return Values

Returns an SQLite3Stmt object on success or FALSE on failure.

Examples

Example #1 SQLite3::prepare() example

<?php
unlink
('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id'1SQLITE3_INTEGER);

$result $stmt->execute();
var_dump($result->fetchArray());
?>

See Also



SQLite3::query

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::queryExecutes an SQL query

Description

public SQLite3::query ( string $query ) : SQLite3Result

Executes an SQL query, returning an SQLite3Result object. If the query does not yield a result (such as DML statements) the returned SQLite3Result object is not really usable. Use SQLite3::exec() for such queries instead.

Parameters

query

The SQL query to execute.

Return Values

Returns an SQLite3Result object, or FALSE on failure.

Examples

Example #1 SQLite3::query() example

<?php
$db 
= new SQLite3('mysqlitedb.db');

$results $db->query('SELECT bar FROM foo');
while (
$row $results->fetchArray()) {
    
var_dump($row);
}
?>



SQLite3::querySingle

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::querySingleExecutes a query and returns a single result

Description

public SQLite3::querySingle ( string $query [, bool $entire_row = FALSE ] ) : mixed

Executes a query and returns a single result.

Parameters

query

The SQL query to execute.

entire_row

By default, querySingle() returns the value of the first column returned by the query. If entire_row is TRUE, then it returns an array of the entire first row.

Return Values

Returns the value of the first column of results or an array of the entire first row (if entire_row is TRUE).

If the query is valid but no results are returned, then NULL will be returned if entire_row is FALSE, otherwise an empty array is returned.

Invalid or failing queries will return FALSE.

Examples

Example #1 SQLite3::querySingle() example

<?php
$db 
= new SQLite3('mysqlitedb.db');

var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1'true));
?>

The above example will output something similar to:

   string(5) "Scott"
   Array
   (
       [username] => Scott
       [email] => scott@example.com
   )
   



SQLite3::version

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::version Returns the SQLite3 library version as a string constant and as a number

Description

public static SQLite3::version ( void ) : array

Returns the SQLite3 library version as a string constant and as a number.

Parameters

This function has no parameters.

Return Values

Returns an associative array with the keys "versionString" and "versionNumber".

Examples

Example #1 SQLite3::version() example

<?php
print_r
(SQLite3::version());
?>

The above example will output something similar to:

   Array
   (
       [versionString] => 3.5.9
       [versionNumber] => 3005009
   )
   


Table of Contents



The SQLite3Stmt class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

A class that handles prepared statements for the SQLite 3 extension.

Class synopsis

SQLite3Stmt {
/* Methods */
public bindParam ( mixed $sql_param , mixed &$param [, int $type ] ) : bool
public bindValue ( mixed $sql_param , mixed $value [, int $type ] ) : bool
public clear ( void ) : bool
public close ( void ) : bool
public execute ( void ) : SQLite3Result
public getSQL ([ bool $expanded = FALSE ] ) : string
public paramCount ( void ) : int
public readOnly ( void ) : bool
public reset ( void ) : bool
}

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::bindParamBinds a parameter to a statement variable

Description

public SQLite3Stmt::bindParam ( mixed $sql_param , mixed &$param [, int $type ] ) : bool

Binds a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, SQLite3Stmt::reset() must be called after the first call to SQLite3Stmt::execute() if the bound value should be properly updated on following calls to SQLite3Stmt::execute(). If SQLite3Stmt::reset() is not called, the bound value will not change, even if the value assigned to the variable passed to SQLite3Stmt::bindParam() has changed, or SQLite3Stmt::bindParam() has been called again.

Parameters

sql_param

Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (:) or an at sign (@), a colon (:) is automatically preprended. Positional parameters start with 1.

param

The parameter to bind to a statement variable.

type

The data type of the parameter to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

As of PHP 7.0.7, if type is omitted, it is automatically detected from the type of the param: boolean and integer are treated as SQLITE3_INTEGER, float as SQLITE3_FLOAT, null as SQLITE3_NULL and all others as SQLITE3_TEXT. Formerly, if type has been omitted, it has defaulted to SQLITE3_TEXT.

Note:

If param is NULL, it is always treated as SQLITE3_NULL, regardless of the given type.

Return Values

Returns TRUE if the parameter is bound to the statement variable, FALSE on failure.

Changelog

Version Description
7.4.0 sql_param now also supports the @param notation.

Examples

Example #1 SQLite3Stmt::bindParam() Usage

This example shows how a single prepared statement with a single parameter binding can be used to insert multiple rows with different values.

<?php
$db 
= new SQLite3(':memory:');
$db->exec("CREATE TABLE foo (bar TEXT)");

$stmt $db->prepare("INSERT INTO foo VALUES (:bar)");
$stmt->bindParam(':bar'$barSQLITE3_TEXT);

$bar 'baz';
$stmt->execute();

$bar 42;
$stmt->execute();

$res $db->query("SELECT * FROM foo");
while ((
$row $res->fetchArray(SQLITE3_ASSOC))) {
    
var_dump($row);
}
?>

The above example will output:

   array(1) {
     ["bar"]=>
     string(3) "baz"
   }
   array(1) {
     ["bar"]=>
     string(2) "42"
   }
   

See Also



SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::bindValueBinds the value of a parameter to a statement variable

Description

public SQLite3Stmt::bindValue ( mixed $sql_param , mixed $value [, int $type ] ) : bool

Binds the value of a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, once the statement has been executed, SQLite3Stmt::reset() needs to be called to be able to change the value of bound parameters.

Parameters

sql_param

Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (:) or an at sign (@), a colon (:) is automatically preprended. Positional parameters start with 1.

value

The value to bind to a statement variable.

type

The data type of the value to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

As of PHP 7.0.7, if type is omitted, it is automatically detected from the type of the value: boolean and integer are treated as SQLITE3_INTEGER, float as SQLITE3_FLOAT, null as SQLITE3_NULL and all others as SQLITE3_TEXT. Formerly, if type has been omitted, it has defaulted to SQLITE3_TEXT.

Note:

If value is NULL, it is always treated as SQLITE3_NULL, regardless of the given type.

Return Values

Returns TRUE if the value is bound to the statement variable, or FALSE on failure.

Changelog

Version Description
7.4.0 sql_param now also supports the @param notation.

Examples

Example #1 SQLite3Stmt::bindValue() example

<?php
$db 
= new SQLite3(':memory:');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id'1SQLITE3_INTEGER);

$result $stmt->execute();
var_dump($result->fetchArray(SQLITE3_ASSOC));
?>

The above example will output:

   array(1) {
     ["bar"]=>
     string(14) "This is a test"
   }
   

See Also



SQLite3Stmt::clear

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::clearClears all current bound parameters

Description

public SQLite3Stmt::clear ( void ) : bool

Clears all current bound parameters (sets them to NULL).

Caution

This method needs to be used with SQLite3Stmt::reset(). If used alone, any call to SQLite3Stmt::bindValue() or SQLite3Stmt::bindParam() will be of no effect and all bound parameters will have the NULL value.

Parameters

This function has no parameters.

Return Values

Returns TRUE on successful clearing of bound parameters, FALSE on failure.



SQLite3Stmt::close

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::closeCloses the prepared statement

Description

public SQLite3Stmt::close ( void ) : bool

Closes the prepared statement.

Note: Note that all SQLite3Results that have been retrieved by executing this statement will be invalidated when the statement is closed.

Parameters

This function has no parameters.

Return Values

Returns TRUE



SQLite3Stmt::execute

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::executeExecutes a prepared statement and returns a result set object

Description

public SQLite3Stmt::execute ( void ) : SQLite3Result

Executes a prepared statement and returns a result set object.

Caution

Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.

Parameters

This function has no parameters.

Return Values

Returns an SQLite3Result object on successful execution of the prepared statement, FALSE on failure.

See Also



SQLite3Stmt::getSQL

(PHP 7 >= 7.4.0)

SQLite3Stmt::getSQLGet the SQL of the statement

Description

public SQLite3Stmt::getSQL ([ bool $expanded = FALSE ] ) : string

Retrieves the SQL of the prepared statement. If expanded is FALSE, the unmodified SQL is retrieved. If expanded is TRUE, all query parameters are replaced with their bound values, or with an SQL NULL, if not already bound.

Parameters

expanded

Whether to retrieve the expanded SQL. Passing TRUE is only supported as of libsqlite 3.14.

Return Values

Returns the SQL of the prepared statement, or FALSE on failure.

Errors/Exceptions

If expanded is TRUE, but the libsqlite version is less than 3.14, an error of level E_WARNING or an Exception is issued, according to SQLite3::enableExceptions().

Examples

Example #1 Inspecting the expanded SQL

<?php
$db 
= new SQLite3(':memory:');
$stmt $db->prepare("SELECT :a, ?, :c");
$stmt->bindValue(':a''foo');
$answer 42;
$stmt->bindParam(2$answer);
var_dump($stmt->getSQL(true));
?>

The above example will output something similar to:

   string(24) "SELECT 'foo', '42', NULL"
   


SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::paramCountReturns the number of parameters within the prepared statement

Description

public SQLite3Stmt::paramCount ( void ) : int

Returns the number of parameters within the prepared statement.

Parameters

This function has no parameters.

Return Values

Returns the number of parameters within the prepared statement.

See Also



SQLite3Stmt::readOnly

(PHP 5 >= 5.3.6, PHP 7)

SQLite3Stmt::readOnlyReturns whether a statement is definitely read only

Description

public SQLite3Stmt::readOnly ( void ) : bool

Returns whether a statement is definitely read only. A statement is considered read only, if it makes no direct changes to the content of the database file. Note that user defined SQL functions might change the database indirectly as a side effect.

Parameters

This function has no parameters.

Return Values

Returns TRUE if a statement is definitely read only, FALSE otherwise.



SQLite3Stmt::reset

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::resetResets the prepared statement

Description

public SQLite3Stmt::reset ( void ) : bool

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the statement is successfully reset, or FALSE on failure.


Table of Contents



The SQLite3Result class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

A class that handles result sets for the SQLite 3 extension.

Class synopsis

SQLite3Result {
/* Methods */
public columnName ( int $column_number ) : string
public columnType ( int $column_number ) : int
public fetchArray ([ int $mode = SQLITE3_BOTH ] ) : array
public finalize ( void ) : bool
public numColumns ( void ) : int
public reset ( void ) : bool
}

SQLite3Result::columnName

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::columnNameReturns the name of the nth column

Description

public SQLite3Result::columnName ( int $column_number ) : string

Returns the name of the column specified by the column_number. Note that the name of a result column is the value of the AS clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified and may change from one release of libsqlite3 to the next.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the string name of the column identified by column_number.



SQLite3Result::columnType

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::columnTypeReturns the type of the nth column

Description

public SQLite3Result::columnType ( int $column_number ) : int

Returns the type of the column identified by column_number.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the data type index of the column identified by column_number (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL).



SQLite3Result::fetchArray

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::fetchArray Fetches a result row as an associative or numerically indexed array or both

Description

public SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] ) : array

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

Parameters

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

  • SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

  • SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  • SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

Return Values

Returns a result row as an associatively or numerically indexed array or both. Alternately will return FALSE if there are no more rows.

The types of the values of the returned array are mapped from SQLite3 types as follows: integers are mapped to integer if they fit into the range PHP_INT_MIN..PHP_INT_MAX, and to string otherwise. Floats are mapped to float, NULL values are mapped to null, and strings and blobs are mapped to string.



SQLite3Result::finalize

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::finalizeCloses the result set

Description

public SQLite3Result::finalize ( void ) : bool

Closes the result set.

Parameters

This function has no parameters.

Return Values

Returns TRUE.



SQLite3Result::numColumns

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::numColumnsReturns the number of columns in the result set

Description

public SQLite3Result::numColumns ( void ) : int

Returns the number of columns in the result set.

Parameters

This function has no parameters.

Return Values

Returns the number of columns in the result set.



SQLite3Result::reset

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::resetResets the result set back to the first row

Description

public SQLite3Result::reset ( void ) : bool

Resets the result set back to the first row.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the result set is successfully reset back to the first row, FALSE on failure.


Table of Contents




Microsoft SQL Server Driver for PHP


Introduction

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.



Installing/Configuring

Table of Contents


Requirements

The SQLSRV extension can be used on the following operating systems:

  • Windows Vista Service Pack 2 or later
  • Windows Server 2008 Service Pack 2 or later
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:

The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.



Installation

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP 5 running on Windows. Since version 4.0 the SQLSRV extension is compatilbe only with PHP 7.0 running on Linux or Windows.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.

SQLSRV Configure Options
Name Default Changeable Changelog
sqlsrv.WarningsReturnAsErrors 1 (TRUE) PHP_INI_ALL Available since SQLSRV 1.0
sqlsrv.LogSubsystems 0 PHP_INI_ALL Available since SQLSRV 1.0
sqlsrv.LogSeverity 1 PHP_INI_ALL Available since SQLSRV 1.0



Resource Types

Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SQLSRV_FETCH_ASSOC (integer)
Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
SQLSRV_FETCH_NUMERIC (integer)
Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
SQLSRV_FETCH_BOTH (integer)
Forces sqlsrv_fetch_array() to return an array with both associative and numeric keys when passed as a parameter (the default behavior).
SQLSRV_ERR_ALL (integer)
Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (integer)
Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
SQLSRV_ERR_WARNINGS (integer)
Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (integer)
Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (integer)
Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (integer)
Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (integer)
Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (integer)
Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (integer)
Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (integer)
Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (integer)
Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (integer)
Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (integer)
Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (integer)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (integer)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (integer)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (integer)
Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_INOUT (integer)
Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_OUT (integer)
Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (integer)
Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (integer)
Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (integer)
Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (integer)
Specifies a PHP stream. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STRING (integer)
Specifies a string PHP data type. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_BINARY (integer)
Specifies that data is returned as a raw byte stream from the server without performing encoding or translation. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_CHAR (integer)
Data is returned in 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This is the default encoding. For usage information, see » How to: Specify PHP Types.
UTF-8 (integer)
Specifies that data is returned with UTF-8 encoding. For usage information, see » How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (integer)
Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (integer)
Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (integer)
Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (integer)
Describes the char SQL Server data type. This constant works like a function and accepts a parameter indicating the number characters. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATE (integer)
Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (integer)
Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (integer)
Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (integer)
Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (integer)
Describes the decimal SQL Server data type. This constant works like a function and accepts two parameters indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_FLOAT (integer)
Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (integer)
Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (integer)
Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (integer)
Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (integer)
Describes the nchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NUMERIC (integer)
Describes the numeric SQL Server data type. This constant works like a function and accepts two parameter indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR (integer)
Describes the nvarchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR('max') (integer)
Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (integer)
Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (integer)
Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (integer)
Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (integer)
Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (integer)
Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (integer)
Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (integer)
Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (integer)
Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (integer)
Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (integer)
Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (integer)
Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (integer)
Describes the varbinary SQL Server data type. This constant works like a function and accepts a single parameter indicating the byte count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY('max') (integer)
Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (integer)
Describes the varchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR('max') (integer)
Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (integer)
Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (integer)
Indicates a transaction isolation level of READ UNCOMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_READ_COMMITTED (integer)
Indicates a transaction isolation level of READ COMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_REPEATABLE_READ (integer)
Indicates a transaction isolation level of REPEATABLE READ. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_SNAPSHOT (integer)
Indicates a transaction isolation level of SNAPSHOT. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_READ_SERIALIZABLE (integer)
Indicates a transaction isolation level of SERIALIZABLE. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_CURSOR_FORWARD (integer)
Indicates a forward-only cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_STATIC (integer)
Indicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_DYNAMIC (integer)
Indicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_KEYSET (integer)
Indicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_BUFFERED (integer)
Creates a client-side cursor query. Lets you access rows in any order. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.



SQLSRV Functions


sqlsrv_begin_transaction

(No version information available, might only be in Git)

sqlsrv_begin_transactionBegins a database transaction

Description

sqlsrv_begin_transaction ( resource $conn ) : bool

The transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

Parameters

conn

The connection resource returned by a call to sqlsrv_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_begin_transaction() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction$conn ) === false ) {
     die( 
print_rsqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId 1$qty 10$productId 100;

/* Set up and execute the first query. */
$sql1 "INSERT INTO OrdersTable (ID, Quantity, ProductID)
          VALUES (?, ?, ?)"
;
$params1 = array( $orderId$qty$productId );
$stmt1 sqlsrv_query$conn$sql1$params1 );

/* Set up and execute the second query. */
$sql2 "UPDATE InventoryTable 
          SET Quantity = (Quantity - ?) 
          WHERE ProductID = ?"
;
$params2 = array($qty$productId);
$stmt2 sqlsrv_query$conn$sql2$params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     
sqlsrv_commit$conn );
     echo 
"Transaction committed.<br />";
} else {
     
sqlsrv_rollback$conn );
     echo 
"Transaction rolled back.<br />";
}
?>

The above example will output something similar to:

See Also

  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction



sqlsrv_cancel

(No version information available, might only be in Git)

sqlsrv_cancelCancels a statement

Description

sqlsrv_cancel ( resource $stmt ) : bool

Cancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.

Parameters

stmt

The statement resource to be cancelled.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_cancel() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT Sales FROM Table_1";

$stmt sqlsrv_prepare$conn$sql);

if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

if( 
sqlsrv_execute$stmt ) === false) {
     die( 
print_rsqlsrv_errors(), true));
}

$salesTotal 0;
$count 0;

while( (
$row sqlsrv_fetch_array$stmt)) && $salesTotal <=100000)
{
     
$qty $row[0];
     
$price $row[1];
     
$salesTotal += ( $price $qty);
     
$count++;
}

echo 
"$count sales accounted for the first $$salesTotal in revenue.<br />";

// Cancel the pending results. The statement can be reused.
sqlsrv_cancel$stmt);
?>

Notes

The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

See Also



sqlsrv_client_info

(No version information available, might only be in Git)

sqlsrv_client_infoReturns information about the client and specified connection

Description

sqlsrv_client_info ( resource $conn ) : array

Returns information about the client and specified connection

Parameters

conn

The connection about which information is returned.

Return Values

Returns an associative array with keys described in the table below. Returns FALSE otherwise.
Array returned by sqlsrv_client_info
Key Description
DriverDllName SQLNCLI10.DLL
DriverODBCVer ODBC version (xx.yy)
DriverVer SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer php_sqlsrv.dll version (2.0.xxx.x)

Examples

Example #1 sqlsrv_client_info() example

<?php
$serverName 
"serverName\sqlexpress";
$connOptions = array("UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connOptions );

if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true));
}

if( 
$client_info sqlsrv_client_info$conn)) {
    foreach( 
$client_info as $key => $value) {
        echo 
$key.": ".$value."<br />";
    }
} else {
    echo 
"Error in retrieving client info.<br />";
}
?>

See Also



sqlsrv_close

(No version information available, might only be in Git)

sqlsrv_closeCloses an open connection and releases resourses associated with the connection

Description

sqlsrv_close ( resource $conn ) : bool

Closes an open connection and releases resourses associated with the connection.

Parameters

conn

The connection to be closed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_close() example

<?php
$serverName 
"serverName\sqlexpres";
$connOptions = array("UID"=>"username""PWD"=>"password""Database"=>"dbname");
$conn sqlsrv_connect$serverName$connOptions );
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

//-------------------------------------
// Perform database operations here.
//-------------------------------------

// Close the connection.
sqlsrv_close$conn );
?>

See Also



sqlsrv_commit

(No version information available, might only be in Git)

sqlsrv_commitCommits a transaction that was begun with sqlsrv_begin_transaction()

Description

sqlsrv_commit ( resource $conn ) : bool

Commits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

Parameters

conn

The connection on which the transaction is to be committed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_commit() example

The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction$conn ) === false ) {
     die( 
print_rsqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId 1$qty 10$productId 100;

/* Set up and execute the first query. */
$sql1 "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)"
;
$params1 = array( $orderId$qty$productId );
$stmt1 sqlsrv_query$conn$sql1$params1 );

/* Set up and execute the second query. */
$sql2 "UPDATE InventoryTable 
         SET Quantity = (Quantity - ?) 
         WHERE ProductID = ?"
;
$params2 = array($qty$productId);
$stmt2 sqlsrv_query$conn$sql2$params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     
sqlsrv_commit$conn );
     echo 
"Transaction committed.<br />";
} else {
     
sqlsrv_rollback$conn );
     echo 
"Transaction rolled back.<br />";
}
?>

See Also



sqlsrv_configure

(No version information available, might only be in Git)

sqlsrv_configureChanges the driver error handling and logging configurations

Description

sqlsrv_configure ( string $setting , mixed $value ) : bool

Changes the driver error handling and logging configurations.

Parameters

setting

The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".

value

The value of the specified setting. The following table shows possible values:
Error and Logging Setting Options
Setting Options
WarningsReturnAsErrors 1 (TRUE) or 0 (FALSE)
LogSubsystems SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8)
LogSeverity SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2)

Return Values

Returns TRUE on success or FALSE on failure.



sqlsrv_connect

(No version information available, might only be in Git)

sqlsrv_connectOpens a connection to a Microsoft SQL Server database

Description

sqlsrv_connect ( string $serverName [, array $connectionInfo ] ) : resource

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.

Parameters

serverName

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward slash and the instance name (e.g. serverName\sqlexpress).

connectionInfo

An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

Return Values

A connection resource. If a connection cannot be successfully opened, FALSE is returned.

Examples

Example #1 Connect using Windows Authentication.

<?php
$serverName 
"serverName\\sqlexpress"//serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn sqlsrv_connect$serverName$connectionInfo);

if( 
$conn ) {
     echo 
"Connection established.<br />";
}else{
     echo 
"Connection could not be established.<br />";
     die( 
print_rsqlsrv_errors(), true));
}
?>

Example #2 Connect by specifying a user name and password.

<?php
$serverName 
"serverName\\sqlexpress"//serverName\instanceName
$connectionInfo = array( "Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);

if( 
$conn ) {
     echo 
"Connection established.<br />";
}else{
     echo 
"Connection could not be established.<br />";
     die( 
print_rsqlsrv_errors(), true));
}
?>

Example #3 Connect on a specified port.

<?php
$serverName 
"serverName\\sqlexpress, 1542"//serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);

if( 
$conn ) {
     echo 
"Connection established.<br />";
}else{
     echo 
"Connection could not be established.<br />";
     die( 
print_rsqlsrv_errors(), true));
}
?>

Notes

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or FALSE). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).

See Also

  • sqlsrv_close() - Closes an open connection and releases resourses associated with the connection
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_query() - Prepares and executes a query



sqlsrv_errors

(No version information available, might only be in Git)

sqlsrv_errorsReturns error and warning information about the last SQLSRV operation performed

Description

sqlsrv_errors ([ int $errorsOrWarnings ] ) : mixed

Returns error and warning information about the last SQLSRV operation performed.

Parameters

errorsOrWarnings

Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.

Return Values

If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred on the last sqlsrv operation, NULL is returned. The following table describes the structure of the returned arrays:
Array returned by sqlsrv_errors
Key Description
SQLSTATE For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP.
code For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code.
message A description of the error.

Examples

Example #1 functionname() example

<?php
$serverName 
"serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

/* Set up a query to select an invalid column name. */
$sql "SELECT BadColumnName FROM Table_1";

/* Execution of the query will fail because of the bad column name. */
$stmt sqlsrv_query$conn$sql );
if( 
$stmt === false ) {
    if( (
$errors sqlsrv_errors() ) != null) {
        foreach( 
$errors as $error ) {
            echo 
"SQLSTATE: ".$error'SQLSTATE']."<br />";
            echo 
"code: ".$error'code']."<br />";
            echo 
"message: ".$error'message']."<br />";
        }
    }
}
?>

Notes

By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns FALSE. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see sqlsrv_configure() and the WarningsReturnAsErrors setting.

See Also



sqlsrv_execute

(No version information available, might only be in Git)

sqlsrv_executeExecutes a statement prepared with sqlsrv_prepare()

Description

sqlsrv_execute ( resource $stmt ) : bool

Executes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.

Parameters

stmt

A statement resource returned by sqlsrv_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_execute() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false) {
    die( 
print_rsqlsrv_errors(), true));
}

$sql "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?"
;

// Initialize parameters and prepare the statement. 
// Variables $qty and $id are bound to the statement, $stmt.
$qty 0$id 0;
$stmt sqlsrv_prepare$conn$sql, array( &$qty, &$id));
if( !
$stmt ) {
    die( 
print_rsqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information. 
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>102=>203=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    
// Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement. 
    
if( sqlsrv_execute$stmt ) === false ) {
          die( 
print_rsqlsrv_errors(), true));
    }
}
?>

Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

See Also



sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_arrayReturns a row as an array

Description

sqlsrv_fetch_array ( resource $stmt [, int $fetchType [, int $row [, int $offset ]]] ) : array

Returns the next available row of data as an associative array, a numeric array, or both (the default).

Parameters

stmt

A statement resource returned by sqlsrv_query or sqlsrv_prepare.

fetchType

A predefined constant specifying the type of array to return. Possible values are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and SQLSRV_FETCH_BOTH (the default).

A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.

row

Specifies the row to access in a result set that uses a scrollable cursor. Possible values are SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE and, SQLSRV_SCROLL_RELATIVE (the default). When this parameter is specified, the fetchType must be explicitly defined.

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns an array on success, NULL if there are no more rows to return, and FALSE if an error occurs.

Examples

Example #1 Retrieving an associative array.

<?php
$serverName 
"serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo );
if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT FirstName, LastName FROM SomeTable";
$stmt sqlsrv_query$conn$sql );
if( 
$stmt === false) {
    die( 
print_rsqlsrv_errors(), true) );
}

while( 
$row sqlsrv_fetch_array$stmtSQLSRV_FETCH_ASSOC) ) {
      echo 
$row['LastName'].", ".$row['FirstName']."<br />";
}

sqlsrv_free_stmt$stmt);
?>

Example #2 Retrieving a numeric array.

<?php
$serverName 
"serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo );
if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT FirstName, LastName FROM SomeTable";
$stmt sqlsrv_query$conn$sql );
if( 
$stmt === false) {
    die( 
print_rsqlsrv_errors(), true) );
}

while( 
$row sqlsrv_fetch_array$stmtSQLSRV_FETCH_NUMERIC) ) {
      echo 
$row[0].", ".$row[1]."<br />";
}

sqlsrv_free_stmt$stmt);
?>

Notes

Not specifying the fetchType or explicitly using the SQLSRV_FETCH_TYPE constant in the examples above will return an array that has both associative and numeric keys.

If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.

If a column with no name is returned, the associative key for the array element will be an empty string ("").

See Also



sqlsrv_fetch_object

(No version information available, might only be in Git)

sqlsrv_fetch_objectRetrieves the next row of data in a result set as an object

Description

sqlsrv_fetch_object ( resource $stmt [, string $className [, array $ctorParams [, int $row [, int $offset ]]]] ) : mixed

Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.

Parameters

stmt

A statement resource created by sqlsrv_query() or sqlsrv_execute().

className

The name of the class to instantiate. If no class name is specified, stdClass is instantiated.

ctorParams

Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns an object on success, NULL if there are no more rows to return, and FALSE if an error occurs or if the specified class does not exist.

Examples

Example #1 sqlsrv_fetch_object() example

The following example demonstrates how to retrieve a row as a stdClass object.

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT fName, lName FROM Table_1";
$stmt sqlsrv_query$conn$sql);
if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj sqlsrv_fetch_object$stmt)) {
      echo 
$obj->fName.", ".$obj->lName."<br />";
}
?>

Notes

If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:

  • Field-property name matching is case-sensitive.
  • Field-property matching occurs regardless of access modifiers.
  • Class property data types are ignored when applying a field value to a property.
  • If the class does not exist, the function returns FALSE and adds an error to the error collection.
Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection.

When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().

See Also



sqlsrv_fetch

(No version information available, might only be in Git)

sqlsrv_fetchMakes the next row in a result set available for reading

Description

sqlsrv_fetch ( resource $stmt [, int $row [, int $offset ]] ) : mixed

Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.

Parameters

stmt

A statement resource created by executing sqlsrv_query() or sqlsrv_execute().

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Return Values

Returns TRUE if the next row of a result set was successfully retrieved, FALSE if an error occurs, and NULL if there are no more rows in the result set.

Examples

Example #1 sqlsrv_fetch() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT Name, Comment 
        FROM Table_1
        WHERE ReviewID=1"
;
$stmt sqlsrv_query$conn$sql);
if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch$stmt ) === false) {
     die( 
print_rsqlsrv_errors(), true));
}

// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name sqlsrv_get_field$stmt0);
echo 
"$name: ";

$comment sqlsrv_get_field$stmt1);
echo 
$comment;
?>

See Also



sqlsrv_field_metadata

(No version information available, might only be in Git)

sqlsrv_field_metadataRetrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

Description

sqlsrv_field_metadata ( resource $stmt ) : mixed

Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.

Parameters

stmt

The statement resource for which metadata is returned.

Return Values

Returns an array of arrays on success. Otherwise, FALSE is returned. Each returned array is described by the following table:
Array returned by sqlsrv_field_metadata
Key Description
Name The name of the field.
Type The numeric value for the SQL type.
Size The number of characters for fields of character type, the number of bytes for fields of binary type, or NULL for other types.
Precision The precision for types of variable precision, NULL for other types.
Scale The scale for types of variable scale, NULL for other types.
Nullable An enumeration indicating whether the column is nullable, not nullable, or if it is not known.
For more information, see » sqlsrv_field_metadata in the Microsoft SQLSRV documentation.

Examples

Example #1 sqlsrv_field_metadata() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
   die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT * FROM Table_1";
$stmt sqlsrv_prepare$conn$sql );

foreach( 
sqlsrv_field_metadata$stmt ) as $fieldMetadata ) {
    foreach( 
$fieldMetadata as $name => $value) {
       echo 
"$name$value<br />";
    }
      echo 
"<br />";
}
?>

See Also



sqlsrv_free_stmt

(No version information available, might only be in Git)

sqlsrv_free_stmtFrees all resources for the specified statement

Description

sqlsrv_free_stmt ( resource $stmt ) : bool

Frees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.

Parameters

stmt

The statement for which resources are freed. Note that NULL is a valid parameter value. This allows the function to be called multiple times in a script.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_free_stmt() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$stmt sqlsrv_query$conn"SELECT * FROM Table_1");
if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

/*-------------------------------
     Process query results here.
-------------------------------*/

/* Free the statement resources. */
sqlsrv_free_stmt$stmt);

?>

Notes

The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

See Also



sqlsrv_get_config

(No version information available, might only be in Git)

sqlsrv_get_configReturns the value of the specified configuration setting

Description

sqlsrv_get_config ( string $setting ) : mixed

Returns the value of the specified configuration setting.

Parameters

setting

The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

Return Values

Returns the value of the specified setting. If an invalid setting is specified, FALSE is returned.

See Also



sqlsrv_get_field

(No version information available, might only be in Git)

sqlsrv_get_fieldGets field data from the currently selected row

Description

sqlsrv_get_field ( resource $stmt , int $fieldIndex [, int $getAsType ] ) : mixed

Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

fieldIndex

The index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.

getAsType

The PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.

Return Values

Returns data from the specified field on success. Returns FALSE otherwise.

Examples

Example #1 sqlsrv_get_field() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT Name, Comment 
        FROM Table_1
        WHERE ReviewID=1"
;
$stmt sqlsrv_query$conn$sql);
if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch$stmt ) === false) {
     die( 
print_rsqlsrv_errors(), true));
}

// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name sqlsrv_get_field$stmt0);
echo 
"$name: ";

$comment sqlsrv_get_field$stmt1);
echo 
$comment;
?>

See Also



sqlsrv_has_rows

(No version information available, might only be in Git)

sqlsrv_has_rowsIndicates whether the specified statement has rows

Description

sqlsrv_has_rows ( resource $stmt ) : bool

Indicates whether the specified statement has rows.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Return Values

Returns TRUE if the specified statement has rows and FALSE if the statement does not have rows or if an error occurred.

Examples

Example #1 sqlsrv_has_rows() example

<?php
$server 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" )
$conn sqlsrv_connect$server$connectionInfo );

$stmt sqlsrv_query$conn"SELECT * FROM Table_1");

if (
$stmt) {
   
$rows sqlsrv_has_rows$stmt );
   if (
$rows === true)
      echo 
"There are rows. <br />";
   else 
      echo 
"There are no rows. <br />";
}
?>

See Also



sqlsrv_next_result

(No version information available, might only be in Git)

sqlsrv_next_resultMakes the next result of the specified statement active

Description

sqlsrv_next_result ( resource $stmt ) : mixed

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

Parameters

stmt

The statement on which the next result is being called.

Return Values

Returns TRUE if the next result was successfully retrieved, FALSE if an error occurred, and NULL if there are no more results to retrieve.

Examples

Example #1 sqlsrv_next_result() example

The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);

$query "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1"some data");
$stmt sqlsrv_query($conn$query$params);

// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";

// Move to the next result and display results.
$next_result sqlsrv_next_result($stmt);
if( 
$next_result ) {
   while( 
$row sqlsrv_fetch_array$stmtSQLSRV_FETCH_ASSOC)){
      echo 
$row['id'].": ".$row['data']."<br />"
   }
} elseif( 
is_null($next_result)) {
     echo 
"No more results.<br />";
} else {
     die(
print_r(sqlsrv_errors(), true));
}
?>

See Also



sqlsrv_num_fields

(No version information available, might only be in Git)

sqlsrv_num_fieldsRetrieves the number of fields (columns) on a statement

Description

sqlsrv_num_fields ( resource $stmt ) : mixed

Retrieves the number of fields (columns) on a statement.

Parameters

stmt

The statement for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.

Return Values

Returns the number of fields on success. Returns FALSE otherwise.

Examples

Example #1 sqlsrv_num_fields() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
   die( 
print_rsqlsrv_errors(), true));
}

$sql "SELECT * FROM Table_1";
$stmt sqlsrv_query($conn$sql);
if( 
$stmt === false) {
   die( 
print_rsqlsrv_errors(), true));
}

$numFields sqlsrv_num_fields$stmt );

while( 
sqlsrv_fetch$stmt )) {
   
// Iterate through the fields of each row.
   
for($i 0$i $numFields$i++) { 
      echo 
sqlsrv_get_field($stmt$i)." ";
   }
   echo 
"<br />";
}
?>

See Also



sqlsrv_num_rows

(No version information available, might only be in Git)

sqlsrv_num_rowsRetrieves the number of rows in a result set

Description

sqlsrv_num_rows ( resource $stmt ) : mixed

Retrieves the number of rows in a result set. This function requires that the statement resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Parameters

stmt

The statement for which the row count is returned. The statement resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns the number of rows retrieved on success and FALSE if an error occurred. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.

Examples

Example #1 sqlsrv_num_rows() example

<?php
$server 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" );
$conn sqlsrv_connect$server$connectionInfo );

$sql "SELECT * FROM Table_1";
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt sqlsrv_query$conn$sql $params$options );

$row_count sqlsrv_num_rows$stmt );
   
if (
$row_count === false)
   echo 
"Error in retrieveing row count.";
else
   echo 
$row_count;
?>

See Also



sqlsrv_prepare

(No version information available, might only be in Git)

sqlsrv_preparePrepares a query for execution

Description

sqlsrv_prepare ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed

Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.

Parameters

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element Description
$value A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifying query property options. The supported keys are described in the following table:

Query Options
Key Values Description
QueryTimeout A positive integer value. Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec TRUE or FALSE (the default is TRUE) Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns a statement resource on success and FALSE if an error occurred.

Examples

Example #1 sqlsrv_prepare() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false) {
    die( 
print_rsqlsrv_errors(), true));
}

$sql "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?"
;

// Initialize parameters and prepare the statement. 
// Variables $qty and $id are bound to the statement, $stmt.
$qty 0$id 0;
$stmt sqlsrv_prepare$conn$sql, array( &$qty, &$id));
if( !
$stmt ) {
    die( 
print_rsqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information. 
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>102=>203=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    
// Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement. 
    
if( sqlsrv_execute$stmt ) === false ) {
          die( 
print_rsqlsrv_errors(), true));
    }
}
?>

Notes

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

See Also



sqlsrv_query

(No version information available, might only be in Git)

sqlsrv_queryPrepares and executes a query

Description

sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed

Prepares and executes a query.

Parameters

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element Description
$value A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifying query property options. The supported keys are described in the following table:

Query Options
Key Values Description
QueryTimeout A positive integer value. Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec TRUE or FALSE (the default is TRUE) Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Return Values

Returns a statement resource on success and FALSE if an error occurred.

Examples

Example #1 sqlsrv_query() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" );
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1"some data");

$stmt sqlsrv_query$conn$sql$params);
if( 
$stmt === false ) {
     die( 
print_rsqlsrv_errors(), true));
}
?>

Notes

For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().

See Also



sqlsrv_rollback

(No version information available, might only be in Git)

sqlsrv_rollbackRolls back a transaction that was begun with sqlsrv_begin_transaction()

Description

sqlsrv_rollback ( resource $conn ) : bool

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

Parameters

conn

The connection resource returned by a call to sqlsrv_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sqlsrv_rollback() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"userName""PWD"=>"password");
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
    die( 
print_rsqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction$conn ) === false ) {
     die( 
print_rsqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId 1$qty 10$productId 100;

/* Set up and execute the first query. */
$sql1 "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)"
;
$params1 = array( $orderId$qty$productId );
$stmt1 sqlsrv_query$conn$sql1$params1 );

/* Set up and execute the second query. */
$sql2 "UPDATE InventoryTable 
         SET Quantity = (Quantity - ?) 
         WHERE ProductID = ?"
;
$params2 = array($qty$productId);
$stmt2 sqlsrv_query$conn$sql2$params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     
sqlsrv_commit$conn );
     echo 
"Transaction committed.<br />";
} else {
     
sqlsrv_rollback$conn );
     echo 
"Transaction rolled back.<br />";
}
?>

See Also



sqlsrv_rows_affected

(No version information available, might only be in Git)

sqlsrv_rows_affectedReturns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

Description

sqlsrv_rows_affected ( resource $stmt ) : int

Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().

Parameters

stmt

The executed statement resource for which the number of affected rows is returned.

Return Values

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query. If no rows were affected, 0 is returned. If the number of affected rows cannot be determined, -1 is returned. If an error occurred, FALSE is returned.

Examples

Example #1 sqlsrv_rows_affected() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" );
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "UPDATE Table_1 SET data = ? WHERE id = ?";

$params = array("updated data"1);

$stmt sqlsrv_query$conn$sql$params);

$rows_affected sqlsrv_rows_affected$stmt);
if( 
$rows_affected === false) {
     die( 
print_rsqlsrv_errors(), true));
} elseif( 
$rows_affected == -1) {
      echo 
"No information available.<br />";
} else {
      echo 
$rows_affected." rows were updated.<br />";
}
?>

See Also



sqlsrv_send_stream_data

(No version information available, might only be in Git)

sqlsrv_send_stream_dataSends data from parameter streams to the server

Description

sqlsrv_send_stream_data ( resource $stmt ) : bool

Send data from parameter streams to the server. Up to 8 KB of data is sent with each call.

Parameters

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Return Values

Returns TRUE if there is more data to send and FALSE if there is not.

Examples

Example #1 sqlsrv_send_stream_data() example

<?php
$serverName 
"serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName""UID"=>"username""PWD"=>"password" );
$conn sqlsrv_connect$serverName$connectionInfo);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$sql "UPDATE Table_1 SET data = ( ?) WHERE id = 100";

// Open parameter data as a stream and put it in the $params array.
$data fopen"data://text/plain,[ Lengthy content here. ]""r");
$params = array( &$data);

// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt sqlsrv_prepare$conn$sql$params$options);

sqlsrv_execute$stmt);

// Send up to 8K of parameter data to the server 
// with each call to sqlsrv_send_stream_data.
$i 1;
while( 
sqlsrv_send_stream_data$stmt)) {
      
$i++;
}
echo 
"$i calls were made.";
?>

See Also



sqlsrv_server_info

(No version information available, might only be in Git)

sqlsrv_server_infoReturns information about the server

Description

sqlsrv_server_info ( resource $conn ) : array

Returns information about the server.

Parameters

conn

The connection resource that connects the client and the server.

Return Values

Returns an array as described in the following table:
Returned Array
CurrentDatabase The connected-to database.
SQLServerVersion The SQL Server version.
SQLServerName The name of the server.

Examples

Example #1 sqlsrv_server_info() example

<?php
$serverName 
"serverName\sqlexpress";
$conn sqlsrv_connect$serverName);
if( 
$conn === false ) {
     die( 
print_rsqlsrv_errors(), true));
}

$server_info sqlsrv_server_info$conn);
if( 
$server_info )
{
    foreach( 
$server_info as $key => $value) {
       echo 
$key.": ".$value."<br />";
    }
} else {
      die( 
print_rsqlsrv_errors(), true));
}
?>

See Also


Table of Contents




Sybase


Introduction

Warning

As of PHP 7.0.0, the sybase_ct extension has been removed.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

To enable Sybase-DB support configure PHP --with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.

Note:

As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.

As of PHP 7.0.0, the sybase_ct extension has been removed.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Sybase configuration options
Name Default Changeable Changelog
sybase.allow_persistent "1" PHP_INI_ALL PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent "-1" PHP_INI_ALL PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_links "-1" PHP_INI_ALL PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.interface_file "/usr/sybase/interfaces" PHP_INI_SYSTEM  
sybase.min_error_severity "10" PHP_INI_ALL  
sybase.min_message_severity "10" PHP_INI_ALL  
sybase.compatability_mode "0" PHP_INI_ALL  
magic_quotes_sybase "0" PHP_INI_ALL Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.

Here's a short explanation of the configuration directives.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled. This setting is also respected by addslashes() and stripslashes().

Note:

Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Sybase-CT configuration options
Name Default Changeable Changelog
sybct.deadlock_retry_count "0" PHP_INI_ALL Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.



Resource Types

This extension has no resource types defined.




Predefined Constants

This extension has no constants defined.



Sybase Functions


sybase_affected_rows

(PHP 4, PHP 5)

sybase_affected_rowsGets number of affected rows in last query

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_affected_rows ([ resource $link_identifier ] ) : int

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier.

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns the number of affected rows, as an integer.

Examples

Example #1 Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE''''') or
die(
"Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n"sybase_affected_rows());
?>

The above example will output:

   Records deleted: 10
   

See Also



sybase_close

(PHP 4, PHP 5)

sybase_closeCloses a Sybase connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_close ([ resource $link_identifier ] ) : bool

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



sybase_connect

(PHP 4, PHP 5)

sybase_connectOpens a Sybase server connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_connect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname [, bool $new = FALSE ]]]]]] ) : resource

sybase_connect() establishes a connection to a Sybase server.

In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

new

Whether to open a new connection or use the existing one.

Return Values

Returns a positive Sybase link identifier on success, or FALSE on failure.

Changelog

Version Description
5.3.0 The new parameter was added.

Examples

Example #1 sybase_connect() example

<?php
$link 
sybase_connect('SYBASE''''')
        or die(
"Could not connect !");
echo 
"Connected successfully";
sybase_close($link);
?>

See Also



sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seekMoves internal row pointer

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_data_seek ( resource $result_identifier , int $row_number ) : bool

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

Parameters

result_identifier

row_number

Return Values

Returns TRUE on success or FALSE on failure.

See Also



sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_countSets the deadlock retry count

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_deadlock_retry_count ( int $retry_count ) : void

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Parameters

retry_count

Values for retry_count
-1 Retry forever (default)
0 Do not retry
n Retry n times

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.



sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_arrayFetch row as array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_array ( resource $result ) : array

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note:

When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Examples

Example #1 Identical fieldnames

<?php

$dbh 
sybase_connect('SYBASE''''');
$q sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

   array(4) {
     [0]=>
     int(1)
     ["person_id"]=>
     int(1)
     [1]=>
     int(1)
     ["person_id1"]=>
     int(1)
   }
   

See Also



sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assocFetch a result row as an associative array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_assoc ( resource $result ) : array

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also



sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_fieldGet field information from a result

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_field ( resource $result [, int $field_offset = -1 ] ) : object

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

Return Values

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - datatype of the column

See Also



sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_objectFetch a row as an object

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_object ( resource $result [, mixed $object ] ) : object

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

Parameters

result

object

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 sybase_fetch_object() return as Foo

<?php
    
class Foo {
        var 
$foo$bar$baz;
    }

    
// {...]
    
$qrhsybase_query('SELECT foo, bar, baz FROM example');
    
$foosybase_fetch_object($qrh'Foo');
    
$barsybase_fetch_object($qrh, new Foo());
    
// {...]
?>

See Also



sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_rowGet a result row as an enumerated array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_row ( resource $result ) : array

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

Data types
PHP Sybase
string VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
float NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL NULL

See Also



sybase_field_seek

(PHP 4, PHP 5)

sybase_field_seekSets field offset

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_field_seek ( resource $result , int $field_offset ) : bool

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

field_offset

Return Values

Returns TRUE on success or FALSE on failure.

See Also



sybase_free_result

(PHP 4, PHP 5)

sybase_free_resultFrees result memory

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_free_result ( resource $result ) : bool

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

Return Values

Returns TRUE on success or FALSE on failure.



sybase_get_last_message

(PHP 4, PHP 5)

sybase_get_last_messageReturns the last message from the server

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_get_last_message ( void ) : string

sybase_get_last_message() returns the last message reported by the server.

Return Values

Returns the message as a string.

See Also



sybase_min_client_severity

(PHP 4, PHP 5)

sybase_min_client_severitySets minimum client severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_client_severity ( int $severity ) : void

sybase_min_client_severity() sets the minimum client severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also



sybase_min_error_severity

(PHP 4, PHP 5)

sybase_min_error_severitySets minimum error severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_error_severity ( int $severity ) : void

sybase_min_error_severity() sets the minimum error severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also



sybase_min_message_severity

(PHP 4, PHP 5)

sybase_min_message_severitySets minimum message severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_message_severity ( int $severity ) : void

sybase_min_message_severity() sets the minimum message severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the DB library interface to Sybase, and not with the CT library.

See Also



sybase_min_server_severity

(PHP 4, PHP 5)

sybase_min_server_severitySets minimum server severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_server_severity ( int $severity ) : void

sybase_min_server_severity() sets the minimum server severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also



sybase_num_fields

(PHP 4, PHP 5)

sybase_num_fieldsGets the number of fields in a result set

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_num_fields ( resource $result ) : int

sybase_num_fields() returns the number of fields in a result set.

Parameters

result

Return Values

Returns the number of fields as an integer.

See Also



sybase_num_rows

(PHP 4, PHP 5)

sybase_num_rowsGet number of rows in a result set

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_num_rows ( resource $result ) : int

sybase_num_rows() returns the number of rows in a result set.

Parameters

result

Return Values

Returns the number of rows as an integer.

See Also



sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnectOpen persistent Sybase connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_pconnect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname ]]]]] ) : resource

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

Return Values

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

See Also



sybase_query

(PHP 4, PHP 5)

sybase_querySends a Sybase query

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_query ( string $query [, resource $link_identifier ] ) : mixed

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

link_identifier

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

See Also



sybase_result

(PHP 4, PHP 5)

sybase_resultGet result data

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_result ( resource $result , int $row , mixed $field ) : string

Returns the contents of the cell at the row and offset in the specified Sybase result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives: sybase_fetch_row(), sybase_fetch_array() and sybase_fetch_object().

Parameters

result

row

field

The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Return Values

sybase_result() returns the contents of one cell from a Sybase result set.



sybase_select_db

(PHP 4, PHP 5)

sybase_select_dbSelects a Sybase database

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_select_db ( string $database_name [, resource $link_identifier ] ) : bool

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to sybase_query() will be made on the active database.

Parameters

database_name

link_identifier

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handlerSets the handler called when a server message is raised

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_set_message_handler ( callable $handler [, resource $link_identifier ] ) : bool

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Parameters

handler

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sybase_set_message_handler() callback function

<?php
    
function msg_handler($msgnumber$severity$state$line$text)
    {
        
var_dump($msgnumber$severity$state$line$text);
    }

    
sybase_set_message_handler('msg_handler');
?>

Example #2 sybase_set_message_handler() callback to a class

<?php
    
class Sybase {
        function 
handler($msgnumber$severity$state$line$text)
        {
            
var_dump($msgnumber$severity$state$line$text);
        }
    }

    
$sybase= new Sybase();
    
sybase_set_message_handler(array($sybase'handler'));
?>

Example #3 sybase_set_message_handler() unhandled messages

<?php
    
// Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    
function msg_handler($msgnumber$severity$state$line$text)
    {
        if (
257 == $msgnumber) {
            return 
false;
        }
        
var_dump($msgnumber$severity$state$line$text);
    }

    
sybase_set_message_handler('msg_handler');
?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.



sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_querySend a Sybase query and do not block

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_unbuffered_query ( string $query , resource $link_identifier [, bool $store_result ] ) : resource

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Note:

If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

Parameters

query

link_identifier

store_result

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Return Values

Returns a positive Sybase result identifier on success, or FALSE on error.

Examples

Example #1 sybase_unbuffered_query() example

<?php

$dbh 
sybase_connect('SYBASE''''');
$q sybase_unbuffered_query('select firstname, lastname from huge_table'$dbhfalse);
sybase_data_seek($q10000);
$i 0;

while (
$row sybase_fetch_row($q)) {
    echo 
$row[0], ' '$row[1], '<br />';
    if (
$i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also


Table of Contents




tokyo_tyrant


Introduction

tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.

"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation

Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.



Installing/Configuring

Table of Contents


Requirements

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.



Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/tokyo_tyrant

Configure options

  • --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation
  • --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation
  • --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support

Enabling the extension

The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration

Running Tokyo Tyrant for the session handler

ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'

Note: expire.lua is included in the tokyo_tyrant extension source distribution

Configuring session handler

  • tokyo_tyrant.session_salt="randomlongstring"
  • session.save_handler=tokyo_tyrant
  • session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"

Note: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.

How it works?

The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460

The parts from left to right:

  • Session id - Generated session id
  • Checksum - Checksum of session salt, session id, node id and primary key
  • Node id - The id of the node where the session maps to
  • Primary key - The primary key of the row where the session is stored

The checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.

In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

tokyo_tyrant Configure Options
Name Default Changeable Changelog
tokyo_tyrant.default_timeout 2.0 PHP_INI_ALL
tokyo_tyrant.session_salt NULL PHP_INI_ALL
tokyo_tyrant.key_prefix NULL PHP_INI_ALL
tokyo_tyrant.allow_failover 1 PHP_INI_ALL
tokyo_tyrant.fail_threshold 5 PHP_INI_ALL
tokyo_tyrant.health_check_divisor 1000 PHP_INI_ALL
tokyo_tyrant.php_expiration 0 PHP_INI_ALL

Here's a short explanation of the configuration directives.

tokyo_tyrant.default_timeout integer

Default timeout when connecting to databases

tokyo_tyrant.session_salt string

The secret that is used to salt session id

tokyo_tyrant.key_prefix string

Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.

tokyo_tyrant.allow_failover integer

Whether to allow session failover in case a server dies.

tokyo_tyrant.fail_threshold integer

How many read/write or connection failures is allowed before server is marked as failed.

tokyo_tyrant.health_check_divisor integer

Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.

tokyo_tyrant.php_expiration integer

Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.



Resource Types

This extension has no resource types defined.




Predefined Constants

TokyoTyrant constants



Examples

Basic usage

Example #1 Putting and getting a key-value pair

<?php
$tt 
= new TokyoTyrant("localhost");
$tt->put("key""value");
echo 
$tt->get("key");
?>

The above example will output:

   value
   


The TokyoTyrant class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

The main Tokyo Tyrant class

Class synopsis

TokyoTyrant {
/* Constants */
const integer RDBDEF_PORT = 1978 ;
const integer RDBQC_STREQ = 0 ;
const integer RDBQC_STRINC = 1 ;
const integer RDBQC_STRBW = 2 ;
const integer RDBQC_STREW = 3 ;
const integer RDBQC_STRAND = 4 ;
const integer RDBQC_STROR = 5 ;
const integer RDBQC_STROREQ = 6 ;
const integer RDBQC_STRRX = 7 ;
const integer RDBQC_NUMEQ = 8 ;
const integer RDBQC_NUMGT = 9 ;
const integer RDBQC_NUMGE = 10 ;
const integer RDBQC_NUMLT = 11 ;
const integer RDBQC_NUMLE = 12 ;
const integer RDBQC_NUMBT = 13 ;
const integer RDBQC_NUMOREQ = 14 ;
const integer RDBQC_NEGATE = 16777216 ;
const integer RDBQC_NOIDX = 33554432 ;
const integer RDBQO_STRASC = 0 ;
const integer RDBQO_STRDESC = 1 ;
const integer RDBQO_NUMASC = 2 ;
const integer RDBQO_NUMDESC = 3 ;
const integer RDBIT_LEXICAL = 0 ;
const integer RDBIT_DECIMAL = 1 ;
const integer RDBIT_TOKEN = 2 ;
const integer RDBIT_QGRAM = 3 ;
const integer RDBIT_OPT = 9998 ;
const integer RDBIT_VOID = 9999 ;
const integer RDBIT_KEEP = 16777216 ;
const integer RDBQCFTS_PH = 15 ;
const integer RDBQCFTS_AND = 16 ;
const integer RDBQCFTS_OR = 17 ;
const integer RDBQCFTS_EX = 18 ;
const integer RDBXO_LCKREC = 1 ;
const integer RDBXOLCK_GLB = 2 ;
const integer RDBREC_INT = 1 ;
const integer RDBREC_DBL = 2 ;
const integer RDBMS_UNION = 0 ;
const integer RDBMS_ISECT = 1 ;
const integer RDBMS_DIFF = 2 ;
const integer RDBT_RECON = 1 ;
/* Methods */
public add ( string $key , number $increment [, int $type = 0 ] ) : number
public connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public connectUri ( string $uri ) : TokyoTyrant
public __construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public copy ( string $path ) : TokyoTyrant
public ext ( string $name , int $options , string $key , string $value ) : string
public fwmKeys ( string $prefix , int $max_recs ) : array
public get ( mixed $keys ) : mixed
public getIterator ( void ) : TokyoTyrantIterator
public num ( void ) : int
public out ( mixed $keys ) : TokyoTyrant
public put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public putShl ( string $key , string $value , int $width ) : mixed
public restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public size ( string $key ) : int
public stat ( void ) : array
public sync ( void ) : mixed
public tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public vanish ( void ) : mixed
}

Predefined Constants

TokyoTyrant Constants

TokyoTyrant::RDBDEF_PORT

The default port of the Tokyo Tyrant database

TokyoTyrant::RDBQC_STREQ

string is equal to

TokyoTyrant::RDBQC_STRINC

string is included in

TokyoTyrant::RDBQC_STRBW

string begins with

TokyoTyrant::RDBQC_STREW

string ends with

TokyoTyrant::RDBQC_STRAND

string includes all tokens in

TokyoTyrant::RDBQC_STROR

string includes at least one token in

TokyoTyrant::RDBQC_STROREQ

string is equal to at least one token in

TokyoTyrant::RDBQC_STRRX

string matches regular expressions of

TokyoTyrant::RDBQC_NUMEQ

number is equal to

TokyoTyrant::RDBQC_NUMGT

number is greater than

TokyoTyrant::RDBQC_NUMGE

number is greater than or equal to

TokyoTyrant::RDBQC_NUMLT

number is less than

TokyoTyrant::RDBQC_NUMLE

number is less than or equal to

TokyoTyrant::RDBQC_NUMBT

number is between two tokens of

TokyoTyrant::RDBQC_NUMOREQ

number is equal to at least one token in

TokyoTyrant::RDBQC_NEGATE

negation flag

TokyoTyrant::RDBQC_NOIDX

no index flag

TokyoTyrant::RDBQO_STRASC

string ascending

TokyoTyrant::RDBQO_STRDESC

string descending

TokyoTyrant::RDBQO_NUMASC

number ascending

TokyoTyrant::RDBQO_NUMDESC

number descending

TokyoTyrant::RDBIT_LEXICAL

lexical string

TokyoTyrant::RDBIT_DECIMAL

decimal string

TokyoTyrant::RDBIT_TOKEN

token inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_QGRAM

QGRAM inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_OPT

optimize

TokyoTyrant::RDBIT_VOID

void

TokyoTyrant::RDBIT_KEEP

keep existing index

TokyoTyrant::RDBQCFTS_PH

full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_OR

full-text search with at least one token in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_EX

full-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

Metasearch union between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_OR

Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_EX

Metasearch difference between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBT_RECON

Whether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections

TokyoTyrant::RDBXOLCK_REC

record locking

TokyoTyrant::RDBXOLCK_GLB

global locking

TokyoTyrant::RDBREC_INT

record type int

TokyoTyrant::RDBREC_DBL

record type float (double)

TokyoTyrant::TTE_SUCCESS

success

TokyoTyrant::TTE_INVALID

invalid operation

TokyoTyrant::TTE_NOHOST

host not found

TokyoTyrant::TTE_REFUSED

connection refused

TokyoTyrant::TTE_SEND

send error

TokyoTyrant::TTE_RECV

recv error

TokyoTyrant::TTE_KEEP

record exist

TokyoTyrant::TTE_NOREC

no record found

TokyoTyrant::TTE_MISC

miscellaneous error


TokyoTyrant::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::addAdds to a numeric key

Description

public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number

Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

Returns the new value on success

Examples

Example #1 TokyoTyrant::add() example

<?php
$tt 
= new TokyoTyrant("localhost"TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test"3);

/* String value is converted to double */
echo $tt->add("test""3.5"TokyoTyrant::RDBREC_DBL);
?>

The above example will output something similar to:

   6.5
   

See Also



TokyoTyrant::connect

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectConnect to a database

Description

public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant

Connects to a remote database

Parameters

host

The hostname

port

The port. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connect() example

<?php
$tt 
= new TokyoTyrant();
$tt->connect("localhost"TokyoTyrant::RDBDEF_PORT)->put("test""value");
?>

See Also



TokyoTyrant::connectUri

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectUriConnects to a database

Description

public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant

Connects to a database using an uri

Parameters

uri

An URI to the database. For example tcp://localhost:1979/

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connectUri() example

<?php
$tt 
= new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test""hi");
?>

See Also



TokyoTyrant::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::__constructConstruct a new TokyoTyrant object

Description

public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parameters

host

The hostname. Default: NULL

port

port number. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

Throws TokyoTyrantException if connection to database fails

See Also



TokyoTyrant::copy

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::copyCopies the database

Description

public TokyoTyrant::copy ( string $path ) : TokyoTyrant

Makes a copy of the current database

Parameters

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::copy() example

<?php
$tt 
= new TokyoTyrant("localhost"1978);
$tt->copy("/tmp/foobar.tct");
?>

See Also



TokyoTyrant::ext

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::extExecute a remote script

Description

public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string

Executes a remote script extension.

Parameters

name

Name of the function to execute

options

Either TokyoTyrant::RDBXO_LCKREC for record locking and TokyoTyrant::RDBXO_LCKGLB for global locking.

key

The key to pass to the function

value

The value to pass to the function

Return Values

Returns the result of the script function

Examples

Example #1 TokyoTyrant::ext() example

<?php
$tt 
= new TokyoTyrant("localhost"1978);
echo 
$tt->ext("somefunc"TokyoTyrant::RDBXO_LCKREC"some_key""some_value");
?>



TokyoTyrant::fwmKeys

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::fwmKeysReturns the forward matching keys

Description

public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array

Returns the forward matching keys from the database

Parameters

prefix

Prefix of the keys

max_recs

Maximum records to return

Return Values

Returns an array of matching keys. The values are not returned

Examples

Example #1 TokyoTyrant::fwmKeys() example

<?php

$tt 
= new TokyoTyrant("localhost");

/* Create 20 macthing keys */
for ($i 0$i 20$i++) {
    
$tt->put("key_" $i"value_" $i);
}

/* Create 20 non-macthing keys */
for ($i 0$i 20$i++) {
    
$tt->put("something_" $i"data_" $i);
}

/* Get five matching keys */
var_dump($tt->fwmKeys("key_"5));
?>

The above example will output something similar to:

   array(5) {
     [0]=>
     string(5) "key_5"
     [1]=>
     string(6) "key_14"
     [2]=>
     string(5) "key_6"
     [3]=>
     string(6) "key_15"
     [4]=>
     string(5) "key_7"
   }
   



TokyoTyrant::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::getThe get purpose

Description

public TokyoTyrant::get ( mixed $keys ) : mixed

This method is used to return a value or multiple values. This method accepts a string or an array as a value.

Parameters

keys

A string key or an array of string keys

Return Values

Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.

Examples

Example #1 TokyoTyrant::get() example

<?php
$tt 
= new TokyoTyrant("localhost"1978);
$tt->put("key1""value1");
$tt->put("key2""value2");
var_dump($tt->get(array("key1""key2")));
var_dump($tt->get("key1"));
?>

The above example will output:

   array(2) {
     ["key1"]=>
     string(6) "value1"
     ["key2"]=>
     string(6) "value2"
   }
   string(6) "value1"
   

See Also



TokyoTyrant::getIterator

(No version information available, might only be in Git)

TokyoTyrant::getIteratorGet an iterator

Description

public TokyoTyrant::getIterator ( void ) : TokyoTyrantIterator

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::getIterator() example

<?php
$tt 
= new TokyoTyrant("localhost");
$it $tt->getIterator();

foreach (
$it as $k => $v) {

}
?>

See Also



TokyoTyrant::num

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::numNumber of records in the database

Description

public TokyoTyrant::num ( void ) : int

Returns the number of records in the database

Parameters

This function has no parameters.

Return Values

Returns number of records in the database

Examples

Example #1 TokyoTyrant::num() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

The above example will output something similar to:

   1234
   

See Also



TokyoTyrant::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::outRemoves records

Description

public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant

Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.

Parameters

keys

A string key or an array of string keys

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::out() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

$tt->put("test1""value1");
$tt->put("test2""value2");

$tt->out(array("test1""test2"));
?>

See Also



TokyoTyrant::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putPuts values

Description

public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key exists the value will be replaced with new value.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::put() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->put("key""value");

/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1""key" => "value2"));

/* Get back one key */
echo $tt->get("key");
?>

The above example will output:

   value2
   

See Also



TokyoTyrant::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putCatConcatenates to a record

Description

public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant

Appends a value into existing key or multiple values if keys is an array. The second parameter is mandatory if keys is a string. If the record does not exist a new record is created.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putCat() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key""value");

/* Concatenate single key-value pair */
$tt->putCat("key"" has more data");

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

   value has more data
   

See Also



TokyoTyrant::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putKeepPuts a record

Description

public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key already exists this method throws an exception indicating that the records exists.

Parameters

keys

A string key or an array of key-value pairs

value

The string value

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 tokyotyrant::putKeep() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key""value");

try {
    
$tt->putKeep("key""new value");
} catch (
TokyoTyrantException $e) {
    if (
$e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo 
"Existing record! Not modified\n";
    } else {
        echo 
"Error: " $e->getMessage() , "\n"
    }
}
echo 
$tt->get("key");
?>

The above example will output:

   Existing record! Not modified
   value
   

See Also



TokyoTyrant::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putNrPuts value

Description

public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. This method does not wait for the response from the server.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putNr() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->putNr("key""value");

/* Put key-value pairs */
$tt->putNr(array("key1" => "value1""key2" => "value2"));

/* Get back one key */
echo $tt->get("key1");
?>

The above example will output:

   value1
   

See Also



TokyoTyrant::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putShlConcatenates to a record

Description

public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed

Concatenate to a record and shift to left.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putShl() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key""just a long piece of data");

/* Concatenate and shift to left */
$tt->putShl("key"" and string"15);

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

   data and string
   

See Also



TokyoTyrant::restore

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::restoreRestore the database

Description

public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed

Restore the database from the update log.

Warning

This method is not supported on 32bit platforms.

Parameters

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Return Values

This method returns the current object and throws TokyoTyrantException on failure.



TokyoTyrant::setMaster

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::setMasterSet the replication master

Description

public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed

Sets the replication master of the database

Warning

This method is not supported on 32bit platforms.

Parameters

host

Hostname of the replication master. If NULL the replication is disabled.

port

Port of the replication master

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::setMaster() example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL00);
?>

See Also

  • Classname::Method()



TokyoTyrant::size

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::sizeReturns the size of the value

Description

public TokyoTyrant::size ( string $key ) : int

Returns the size of a value by key

Parameters

key

The key of which size to fetch

Return Values

Returns the size of the key or throw TokyoTyrantException on error

Examples

Example #1 TokyoTyrant::size() example

<?php
$tt 
= new TokyoTyrant("localhost");

$tt->put("test_key""12345");

echo 
$tt->size("test_key");
?>

The above example will output:

   5
   



TokyoTyrant::stat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::statGet statistics

Description

public TokyoTyrant::stat ( void ) : array

Returns statistics of the remote database

Parameters

This function has no parameters.

Return Values

Returns an array of key value pairs describing the statistics

Examples

Example #1 TokyoTyrant::stat() example

<?php
$tt 
= new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

The above example will output something similar to:

   array(19) {
     ["version"]=>
     string(6) "1.1.28"
     ["libver"]=>
     string(3) "311"
     ["protver"]=>
     string(4) "0.91"
     ["os"]=>
     string(5) "Linux"
     ["time"]=>
     string(17) "1247358357.665630"
     ["pid"]=>
     string(5) "14348"
     ["sid"]=>
     string(8) "59025947"
     ["type"]=>
     string(9) "on-memory"
     ["path"]=>
     string(1) "*"
     ["rnum"]=>
     string(1) "4"
     ["size"]=>
     string(6) "262856"
     ["bigend"]=>
     string(1) "0"
     ["fd"]=>
     string(1) "5"
     ["loadavg"]=>
     string(8) "0.000000"
     ["memsize"]=>
     string(8) "77328384"
     ["memrss"]=>
     string(7) "1183744"
     ["ru_real"]=>
     string(13) "162776.042152"
     ["ru_user"]=>
     string(8) "0.476029"
     ["ru_sys"]=>
     string(8) "8.652540"
   }
   

See Also

  • Classname::Method()



TokyoTyrant::sync

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::syncSynchronize the database

Description

public TokyoTyrant::sync ( void ) : mixed

Synchronizes the database on to the physical device

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.



TokyoTyrant::tune

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrant::tuneTunes connection values

Description

public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant

Tunes database connection options.

Parameters

timeout

The objects timeout value (default: 5.0)

options

Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON. It is recommended not to change the second parameter.

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.



TokyoTyrant::vanish

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::vanishEmpties the database

Description

public TokyoTyrant::vanish ( void ) : mixed

Empties a remote database

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::vanish() example

<?php
$tt 
= new TokyoTyrant("localhost");
$tt->vanish();
?>

See Also


Table of Contents



The TokyoTyrantTable class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

Provides an API to the table databases. A table database can be create using the following command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table API is a schemaless database which can store arbitrary amount of key-value pairs under a single primary key.

Class synopsis

TokyoTyrantTable extends TokyoTyrant {
/* Methods */
public add ( string $key , mixed $increment [, string $type ] ) : void
public genUid ( void ) : int
public get ( mixed $keys ) : array
public getIterator ( void ) : TokyoTyrantIterator
public getQuery ( void ) : TokyoTyrantQuery
public out ( mixed $keys ) : void
public put ( string $key , array $columns ) : int
public putCat ( string $key , array $columns ) : void
public putKeep ( string $key , array $columns ) : void
public putNr ( mixed $keys [, string $value ] ) : void
public putShl ( string $key , string $value , int $width ) : void
public setIndex ( string $column , int $type ) : mixed
/* Inherited methods */
public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number
public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant::copy ( string $path ) : TokyoTyrant
public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string
public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array
public TokyoTyrant::get ( mixed $keys ) : mixed
public TokyoTyrant::num ( void ) : int
public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant
public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed
public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::size ( string $key ) : int
public TokyoTyrant::stat ( void ) : array
public TokyoTyrant::sync ( void ) : mixed
public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public TokyoTyrant::vanish ( void ) : mixed
}

TokyoTyrantTable::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::addAdds a record

Description

public TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] ) : void

This method is not supported with table databases.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

This method throws an TokyoTyrantException if used through this class.

See Also



TokyoTyrantTable::genUid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::genUidGenerate unique id

Description

public TokyoTyrantTable::genUid ( void ) : int

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parameters

This function has no parameters.

Return Values

Returns an unique id or throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::genUid() example

<?php
$tt 
= new TokyoTyrantTable("localhost"1122);

echo 
$tt->genUid();
?>

The above example will output something similar to:

   4
   

See Also



TokyoTyrantTable::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getGet a row

Description

public TokyoTyrantTable::get ( mixed $keys ) : array

Gets a row from table database. keys is a single integer for the primary key of the row or an array of integers for multiple rows.

Parameters

keys

The primary key, can be a string or an integer

Return Values

Returns the row as an array

Examples

Example #1 TokyoTyrantTable::get() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   

Notes

Note:

Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.

See Also



TokyoTyrantTable::getIterator

(No version information available, might only be in Git)

TokyoTyrantTable::getIteratorGet an iterator

Description

public TokyoTyrantTable::getIterator ( void ) : TokyoTyrantIterator

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::getIterator() example

<?php
$tt 
= new TokyoTyrantTable("localhost");
$it $tt->getIterator();

foreach (
$it as $k => $v) {
  
var_dump($k$v);
}
?>

See Also



TokyoTyrantTable::getQuery

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getQueryGet a query object

Description

public TokyoTyrantTable::getQuery ( void ) : TokyoTyrantQuery

Get a query object to execute searches on the database

Parameters

This function has no parameters.

Return Values

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::getQuery() example

<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost"1979);

/* Put a few rows */
$table->put(null, array("column1" => "some data""column2" => "more data"));
$table->put(null, array("something" => "value""data" => "good data"));

/* Get query object */
$query $table->getQuery();

/* Add condition to query */
$query->addCond('data'TokyoTyrant::RDBQC_STREQ'good data');

/* Get matching rows */
var_dump($query->search());
?>

The above example will output something similar to:

   array(1) {
     [11]=>
     array(2) {
       ["something"]=>
       string(5) "value"
       ["data"]=>
       string(9) "good data"
     }
   }
   

See Also



TokyoTyrantTable::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::outRemove records

Description

public TokyoTyrantTable::out ( mixed $keys ) : void

Removes records from a table database.

Parameters

keys

A single integer key or an array of integers

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Delete the row */
$tt->out($index);
?>

See Also



TokyoTyrantTable::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putStore a row

Description

public TokyoTyrantTable::put ( string $key , array $columns ) : int

Puts a new row into the database. This method parameters are key which is the primary key of the row, passing NULL will generate a new unique id. value is an array containing the row contents which is usually key value pairs.

Parameters

key

The primary key of the row

columns

The row contents

Return Values

Returns the primary key on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::put() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->put($index, array("column1" => "other data""column2" => "better data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   array(2) {
     ["column1"]=>
     string(10) "other data"
     ["column2"]=>
     string(11) "better data"
   }
   

See Also



TokyoTyrantTable::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putCatConcatenates to a row

Description

public TokyoTyrantTable::putCat ( string $key , array $columns ) : void

This method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.

Parameters

key

The primary key of the row or NULL

columns

Array of row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putCat() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new""new_column" => "other data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   array(3) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
     ["new_column"]=>
     string(10) "other data"
   }
   

See Also



TokyoTyrantTable::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putKeepPut a new record

Description

public TokyoTyrantTable::putKeep ( string $key , array $columns ) : void

Puts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.

Parameters

key

The primary key of the row or NULL

columns

Array of the row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putKeep() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

try {
    
$tt->putKeep($index, array("column1" => "something new""new_column" => "other data"));
} catch (
TokyoTyrantException $e) {
    if (
$e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo 
"Existing record! Not modified\n";
    } else {
        echo 
"Error: " $e->getMessage() , "\n"
    }
}

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output something similar to:

   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   Existing record! Not modified
   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   

See Also



TokyoTyrantTable::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putNrPuts value

Description

public TokyoTyrantTable::putNr ( mixed $keys [, string $value ] ) : void

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

See Also



TokyoTyrantTable::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putShlConcatenates to a record

Description

public TokyoTyrantTable::putShl ( string $key , string $value , int $width ) : void

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method is not supported on table databases.

See Also



TokyoTyrantTable::setIndex

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::setIndexSets index

Description

public TokyoTyrantTable::setIndex ( string $column , int $type ) : mixed

Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes the index.

Parameters

column

The name of the column

type

The index type

Return Values

This method returns the current object and throws TokyoTyrantException on failure.


Table of Contents



The TokyoTyrantQuery class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

This class is used to query the table databases

Class synopsis

TokyoTyrantQuery implements Iterator {
/* Methods */
public addCond ( string $name , int $op , string $expr ) : mixed
public __construct ( TokyoTyrantTable $table )
public count ( void ) : int
public current ( void ) : array
public hint ( void ) : string
public key ( void ) : string
public metaSearch ( array $queries , int $type ) : array
public next ( void ) : array
public out ( void ) : TokyoTyrantQuery
public rewind ( void ) : bool
public search ( void ) : array
public setLimit ([ int $max [, int $skip ]] ) : mixed
public setOrder ( string $name , int $type ) : mixed
public valid ( void ) : bool
}

TokyoTyrantQuery::addCond

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::addCondAdds a condition to the query

Description

public TokyoTyrantQuery::addCond ( string $name , int $op , string $expr ) : mixed

Adds a condition to the query. Condition can be something like: get all keys which value matches expr.

Parameters

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::addCond() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "not here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

   array(2) {
     [1]=>
     array(2) {
       ["column1"]=>
       string(9) "some data"
       ["column2"]=>
       string(14) "something here"
     }
     [4]=>
     array(2) {
       ["column45"]=>
       string(11) "random data"
       ["column2"]=>
       string(25) "something along the lines"
     }
   }
   

See Also

  • Classname::Method()



TokyoTyrantQuery::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::__constructConstruct a new query

Description

public TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parameters

table

TokyoTyrantTable object with active database connection

Return Values

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::__construct() example

<?php
$tt 
= new TokyoTyrantTable("localhost"1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

See Also



TokyoTyrantQuery::count

(No version information available, might only be in Git)

TokyoTyrantQuery::countCounts records

Description

public TokyoTyrantQuery::count ( void ) : int

Returns a count of how many records a query returns.

Parameters

This function has no parameters.

Return Values

Returns a count of matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::count() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "not here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Count the results */
var_dump($query->count());
?>

The above example will output:

   int(2)
   

See Also



TokyoTyrantQuery::current

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::currentReturns the current element

Description

public TokyoTyrantQuery::current ( void ) : array

Returns the current element. Part of Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current row

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo 
"pk: $key, columns: "count($value) ,"\n";
}
?>

The above example will output something similar to:

   pk: 1, columns: 2
   pk: 4, columns: 2
   

See Also



TokyoTyrantQuery::hint

(No version information available, might only be in Git)

TokyoTyrantQuery::hintGet the hint string of the query

Description

public TokyoTyrantQuery::hint ( void ) : string

Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.

Parameters

This function has no parameters.

Return Values

This method always returns a string

Examples

Example #1 TokyoTyrantQuery::hint example

<?php
$tt 
= new TokyoTyrantTable("localhost"1979);
$tt->vanish();

for (
$i 0$i 11$i++) {
     
$tt->put(null, array('a_col' => 'a' $i'b_col' => 'b' $i));
}

$query $tt->getQuery();
$query->addCond('a_col'TokyoTyrant::RDBQC_STRBW'a');

$query->search();
var_dump($query->hint());
?>

The above example will output something similar to:

   string(72) "
   scanning the whole table
   result set size: 11
   leaving the natural order
   "
   

See Also



TokyoTyrantQuery::key

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::keyReturns the current key

Description

public TokyoTyrantQuery::key ( void ) : string

Returns the current key. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current key and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo 
"pk: $key, columns: "count($value) ,"\n";
}
?>

The above example will output something similar to:

   pk: 1, columns: 2
   pk: 4, columns: 2
   

See Also



TokyoTyrantQuery::metaSearch

(No version information available, might only be in Git)

TokyoTyrantQuery::metaSearchRetrieve records with multiple queries

Description

public TokyoTyrantQuery::metaSearch ( array $queries , int $type ) : array

Executes multiple queries on a database and returns matching records. The current object is always the left most object in the search.

Parameters

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::metaSearch() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add test data */
$tt->put('cherry',     array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple',      array('color' => 'green'));
$tt->put('lemon',      array('color' => 'yellow'));

/* First query */
$query $tt->getQuery();
$query->addCond('color'TokyoTyrant::RDBQC_STREQ'red')->setOrder('color'TokyoTyrant::RDBQO_STRASC);

/* Second query */
$query1 $tt->getQuery();
$query1->addCond('color'TokyoTyrant::RDBQC_STREQ'yellow');

/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>

The above example will output:

   array(3) {
     ["cherry"]=>
     array(1) {
       ["color"]=>
       string(3) "red"
     }
     ["strawberry"]=>
     array(1) {
       ["color"]=>
       string(3) "red"
     }
     ["lemon"]=>
     array(1) {
       ["color"]=>
       string(6) "yellow"
     }
   }
   

See Also



TokyoTyrantQuery::next

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::nextMoves the iterator to next entry

Description

public TokyoTyrantQuery::next ( void ) : array

Returns the next result in the resultset. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns the next row and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo 
"pk: $key, columns: "count($value) ,"\n";
}
?>

The above example will output something similar to:

   pk: 1, columns: 2
   pk: 4, columns: 2
   

See Also



TokyoTyrantQuery::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::outRemoves records based on query

Description

public TokyoTyrantQuery::out ( void ) : TokyoTyrantQuery

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Remove matching records */
$query->out();
?>

See Also



TokyoTyrantQuery::rewind

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::rewindRewinds the iterator

Description

public TokyoTyrantQuery::rewind ( void ) : bool

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns TRUE

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo 
"pk: $key, columns: "count($value) ,"\n";
}
?>

The above example will output something similar to:

   pk: 1, columns: 2
   pk: 4, columns: 2
   

See Also



TokyoTyrantQuery::search

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::searchSearches records

Description

public TokyoTyrantQuery::search ( void ) : array

Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.

Parameters

This function has no parameters.

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::search() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "not here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

   array(2) {
     [1]=>
     array(2) {
       ["column1"]=>
       string(9) "some data"
       ["column2"]=>
       string(14) "something here"
     }
     [4]=>
     array(2) {
       ["column45"]=>
       string(11) "random data"
       ["column2"]=>
       string(25) "something along the lines"
     }
   }
   

See Also



TokyoTyrantQuery::setLimit

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setLimitLimit results

Description

public TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] ) : mixed

Set the maximum amount of records to return on a query.

Parameters

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Return Values

This method returns the current object and throws TokyoTyrantException on failure.



TokyoTyrantQuery::setOrder

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setOrderOrders results

Description

public TokyoTyrantQuery::setOrder ( string $name , int $type ) : mixed

Sets the order of a query

Parameters

name

The column name to apply the ordering on.

type

The type can be one of the following constants:

  • TokyoTyrant::RDBQO_STRASC - String ascending
  • TokyoTyrant::RDBQO_STRDESC - String descending
  • TokyoTyrant::RDBQO_NUMASC - Numberic ascending
  • TokyoTyrant::RDBQO_NUMDESC - String descending

Return Values

This method returns the current object.



TokyoTyrantQuery::valid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::validChecks the validity of current item

Description

public TokyoTyrantQuery::valid ( void ) : bool

Checks if the current item is valid. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Add rows */
$tt->put(null, array("column1" => "some data""column2" => "something here"));
$tt->put(null, array("column1" => "more data""column2" => "best data this far"));
$tt->put(null, array("column1" => "again data""column3" => "foobar here"));
$tt->put(null, array("column45" => "random data""column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data""column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data""column2" => "value here"));

/* Get a new query object */
$query $tt->getQuery();

/* Add a search condition */
$query->addCond("column2"TokyoTyrant::RDBQC_STROR"something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo 
"pk: $key, columns: "count($value) ,"\n";
}
?>

The above example will output something similar to:

   pk: 1, columns: 2
   pk: 4, columns: 2
   

See Also


Table of Contents



The TokyoTyrantIterator class

(PECL tokyo_tyrant >= 0.2.0)

Introduction

Provides an iterator for TokyoTyrant and TokyoTyrantTable objects. The iterator iterates over all keys and values in the database. TokyoTyrantIterator was added in version 0.2.0.

Class synopsis

TokyoTyrantIterator implements Iterator {
/* Methods */
public __construct ( mixed $object )
public current ( void ) : mixed
public key ( void ) : mixed
public next ( void ) : mixed
public rewind ( void ) : void
public valid ( void ) : bool
/* Inherited methods */
public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number
public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant::copy ( string $path ) : TokyoTyrant
public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string
public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array
public TokyoTyrant::get ( mixed $keys ) : mixed
public TokyoTyrant::num ( void ) : int
public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant
public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed
public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::size ( string $key ) : int
public TokyoTyrant::stat ( void ) : array
public TokyoTyrant::sync ( void ) : mixed
public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public TokyoTyrant::vanish ( void ) : mixed
}

TokyoTyrantIterator::__construct

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::__constructConstruct an iterator

Description

public TokyoTyrantIterator::__construct ( mixed $object )

Construct a new TokyoTyrantIterator object. One connection can have multiple iterators but it is not quaranteed that all items are traversed in that case. object parameter can be either an of instance TokyoTyrant or TokyoTyrantTable.

Parameters

This function has no parameters.

Return Values

Throws an exception if iterator initialization fails.

Examples

Example #1 TokyoTyrantIterator::__construct() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost"1979);

/* Passing null to put generates a new uid */
$index $tt->put(null, array("column1" => "some data""column2" => "more data"));

/* Construct an iterator */
$it = new TokyoTyrantIterator($tt);

foreach (
$it as $value) {
    
var_dump($value);
}
?>

The above example will output:

   array(2) {
     ["column1"]=>
     string(9) "some data"
     ["column2"]=>
     string(9) "more data"
   }
   

See Also



TokyoTyrantIterator::current

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::currentGet the current value

Description

public TokyoTyrantIterator::current ( void ) : mixed

Returns the current value during iteration.

Parameters

This function has no parameters.

Return Values

Returns the current value on success and false on failure.

See Also



TokyoTyrantIterator::key

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::keyReturns the current key

Description

public TokyoTyrantIterator::key ( void ) : mixed

Returns the current key.

Parameters

This function has no parameters.

Return Values

Returns the current key on success and false on failure.

See Also



TokyoTyrantIterator::next

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::nextMove to next key

Description

public TokyoTyrantIterator::next ( void ) : mixed

Move to next key during iteration and return it's value.

Parameters

This function has no parameters.

Return Values

Returns the next value on success and false on failure.

See Also



TokyoTyrantIterator::rewind

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::rewindRewinds the iterator

Description

public TokyoTyrantIterator::rewind ( void ) : void

Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.

Parameters

This function has no parameters.

Return Values

Throws TokyoTyrantException if iterator initialization fails.

See Also



TokyoTyrantIterator::valid

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::validRewinds the iterator

Description

public TokyoTyrantIterator::valid ( void ) : bool

Checks whether the internal pointer points to valid element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

See Also


Table of Contents



The TokyoTyrantException class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

TokyoTyrantException

Class synopsis

tokyotyrantexception extends Exception {
/* Properties */
protected int code ;
/* Inherited properties */
protected string message ;
protected int code ;
protected string file ;
protected int line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

code

The exception code. This can be compared to TokyoTyrant::TTE_* constants






Date and Time Related Extensions


Calendar


Introduction

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

To get these functions to work, you have to compile PHP with --enable-calendar.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CAL_EASTER_DEFAULT (integer)
For easter_days(): calculate Easter for years before 1753 according to the Julian calendar, and for later years according to the Gregorian calendar.
CAL_EASTER_ROMAN (integer)
For easter_days(): calculate Easter for years before 1583 according to the Julian calendar, and for later years according to the Gregorian calendar.
CAL_EASTER_ALWAYS_GREGORIAN (integer)
For easter_days(): calculate Easter according to the proleptic Gregorian calendar.
CAL_EASTER_ALWAYS_JULIAN (integer)
For easter_days(): calculate Easter according to the Julian calendar.
CAL_GREGORIAN (integer)
For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the proleptic Gregorian calendar.
CAL_JULIAN (integer)
For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the Julian calendar.
CAL_JEWISH (integer)
For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the Jewish calendar.
CAL_FRENCH (integer)
For cal_days_in_month(), cal_from_jd(), cal_info() and cal_to_jd(): use the French Repuclican calendar.
CAL_NUM_CALS (integer)
The number of available calendars.
CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
For jdtojewish(): adds a geresh symbol (which resembles a single-quote mark) as thousands separator to the year number.
CAL_JEWISH_ADD_ALAFIM (integer)
For jdtojewish(): adds the word alafim as thousands separator to the year number.
CAL_JEWISH_ADD_GERESHAYIM (integer)
For jdtojewish(): add a gershayim symbol (which resembles a double-quote mark) before the final letter of the day and year numbers.
CAL_DOW_DAYNO (integer)
For jddayofweek(): the day of the week as integer, where 0 means Sunday and 6 means Saturday.
CAL_DOW_SHORT (integer)
For jddayofweek(): the abbreviated English name of the day of the week.
CAL_DOW_LONG (integer)
For jddayofweek(): the English name of the day of the week.
CAL_MONTH_GREGORIAN_SHORT (integer)
For jdmonthname(): the abbreviated Gregorian month name.
CAL_MONTH_GREGORIAN_LONG (integer)
For jdmonthname(): the Gregorian month name.
CAL_MONTH_JULIAN_SHORT (integer)
For jdmonthname(): the abbreviated Julian month name.
CAL_MONTH_JULIAN_LONG (integer)
For jdmonthname(): the Julian month name.
CAL_MONTH_JEWISH (integer)
For jdmonthname(): the Jewish month name.
CAL_MONTH_FRENCH (integer)
For jdmonthname(): the French Republican month name.


Calendar Functions


cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_days_in_monthReturn the number of days in a month for a given year and calendar

Description

cal_days_in_month ( int $calendar , int $month , int $year ) : int

This function will return the number of days in the month of year for the specified calendar.

Parameters

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Return Values

The length in days of the selected month in the given calendar

Examples

Example #1 cal_days_in_month() example

<?php
$number 
cal_days_in_month(CAL_GREGORIAN82003); // 31
echo "There were {$number} days in August 2003";
?>



cal_from_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_from_jdConverts from Julian Day Count to a supported calendar

Description

cal_from_jd ( int $jd , int $calendar ) : array

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

jd

Julian day as integer

calendar

Calendar to convert to

Return Values

Returns an array containing calendar information like month, day, year, day of week (dow), abbreviated and full names of weekday and month and the date in string form "month/day/year". The day of week ranges from 0 (Sunday) to 6 (Saturday).

Examples

Example #1 cal_from_jd() example

<?php
$today 
unixtojd(mktime(0008162003));
print_r(cal_from_jd($todayCAL_GREGORIAN));
?>

The above example will output:

   Array
   (
       [date] => 8/16/2003
       [month] => 8
       [day] => 16
       [year] => 2003
       [dow] => 6
       [abbrevdayname] => Sat
       [dayname] => Saturday
       [abbrevmonth] => Aug
       [monthname] => August
   )
   

See Also

  • cal_to_jd() - Converts from a supported calendar to Julian Day Count
  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix() - Convert Julian Day to Unix timestamp



cal_info

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_infoReturns information about a particular calendar

Description

cal_info ([ int $calendar = -1 ] ) : array

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parameters

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Return Values

Examples

Example #1 cal_info() example

<?php
$info 
cal_info(0);
print_r($info);
?>

The above example will output:

   Array
   (
       [months] => Array
           (
               [1] => January
               [2] => February
               [3] => March
               [4] => April
               [5] => May
               [6] => June
               [7] => July
               [8] => August
               [9] => September
               [10] => October
               [11] => November
               [12] => December
           )
   
       [abbrevmonths] => Array
           (
               [1] => Jan
               [2] => Feb
               [3] => Mar
               [4] => Apr
               [5] => May
               [6] => Jun
               [7] => Jul
               [8] => Aug
               [9] => Sep
               [10] => Oct
               [11] => Nov
               [12] => Dec
           )
   
       [maxdaysinmonth] => 31
       [calname] => Gregorian
       [calsymbol] => CAL_GREGORIAN
   )
   



cal_to_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_to_jdConverts from a supported calendar to Julian Day Count

Description

cal_to_jd ( int $calendar , int $month , int $day , int $year ) : int

cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

Return Values

A Julian Day number.

See Also

  • cal_from_jd() - Converts from Julian Day Count to a supported calendar
  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • unixtojd() - Convert Unix timestamp to Julian Day



easter_date

(PHP 4, PHP 5, PHP 7)

easter_dateGet Unix timestamp for midnight on Easter of a given year

Description

easter_date ([ int $year = date("Y") [, int $method = CAL_EASTER_DEFAULT ]] ) : int

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Warning

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. typically before 1970 or after 2037 on 32bit systems).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

Parameters

year

The year as a number between 1970 an 2037. If omitted, defaults to the current year according to the local time.

method

Allows Easter dates to be calculated based on the Julian calendar when set to CAL_EASTER_ALWAYS_JULIAN. See also calendar constants.

Return Values

The easter date as a unix timestamp.

Examples

Example #1 easter_date() example

<?php

echo date("M-d-Y"easter_date(1999));        // Apr-04-1999
echo date("M-d-Y"easter_date(2000));        // Apr-23-2000
echo date("M-d-Y"easter_date(2001));        // Apr-15-2001

?>

Notes

Note:

easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the TZ environment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.

As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:

<?php
function get_easter_datetime($year) {
    
$base = new DateTime("$year-03-21");
    
$days easter_days($year);

    return 
$base->add(new DateInterval("P{$days}D"));
}

foreach (
range(20122015) as $year) {
    
printf("Easter in %d is on %s\n",
           
$year,
           
get_easter_datetime($year)->format('F j'));
}
?>

The above example will output:

   Easter in 2012 is on April 8
   Easter in 2013 is on March 31
   Easter in 2014 is on April 20
   Easter in 2015 is on April 5
   

See Also

  • easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037



easter_days

(PHP 4, PHP 5, PHP 7)

easter_daysGet number of days after March 21 on which Easter falls for a given year

Description

easter_days ([ int $year = date("Y") [, int $method = CAL_EASTER_DEFAULT ]] ) : int

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

Parameters

year

The year as a positive number. If omitted, defaults to the current year according to the local time.

method

Allows Easter dates to be calculated based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Return Values

The number of days after March 21st that the Easter Sunday is in the given year.

Examples

Example #1 easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

See Also

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year



frenchtojd

(PHP 4, PHP 5, PHP 7)

frenchtojdConverts a date from the French Republican Calendar to a Julian Day Count

Description

frenchtojd ( int $month , int $day , int $year ) : int

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

Parameters

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

Return Values

The julian day for the given french revolution date as an integer.

See Also

  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



gregoriantojd

(PHP 4, PHP 5, PHP 7)

gregoriantojdConverts a Gregorian date to Julian Day Count

Description

gregoriantojd ( int $month , int $day , int $year ) : int

The valid range for the Gregorian calendar is from November 25, 4714 B.C. to at least December 31, 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31. If the month has less days then given, overflow occurs; see the example below.

year

The year as a number between -4714 and 9999. Negative numbers mean years B.C., positive numbers mean years A.D. Note that there is no year 0; December 31, 1 B.C. is immediately followed by January 1, 1 A.D.

Return Values

The julian day for the given gregorian date as an integer. Dates outside the valid range return 0.

Examples

Example #1 Calendar functions

<?php
$jd 
gregoriantojd(10111970);
echo 
"$jd\n";
$gregorian jdtogregorian($jd);
echo 
"$gregorian\n";
?>

The above example will output:

   2440871
   10/11/1970
   

Example #2 Overflow behavior

<?php
echo gregoriantojd(2312018), PHP_EOL,
     
gregoriantojd(3,  32018), PHP_EOL;
?>

The above example will output:

   2458181
   2458181
   

See Also

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



jddayofweek

(PHP 4, PHP 5, PHP 7)

jddayofweekReturns the day of the week

Description

jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] ) : mixed

Returns the day of the week. Can return a string or an integer depending on the mode.

Parameters

julianday

A julian day number as integer

mode
Calendar week modes
Mode Meaning
0 (Default) Return the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Return a string containing the abbreviated day of week (English-Gregorian)

Return Values

The gregorian weekday as either an integer or string.



jdmonthname

(PHP 4, PHP 5, PHP 7)

jdmonthnameReturns a month name

Description

jdmonthname ( int $julianday , int $mode ) : string

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.
Calendar modes
Mode Meaning Values
CAL_MONTH_GREGORIAN_SHORT Gregorian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
CAL_MONTH_GREGORIAN_LONG Gregorian January, February, March, April, May, June, July, August, September, October, November, December
CAL_MONTH_JULIAN_SHORT Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
CAL_MONTH_JULIAN_LONG Julian January, February, March, April, May, June, July, August, September, October, November, December
CAL_MONTH_JEWISH Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
CAL_MONTH_FRENCH French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

Parameters

jday

The Julian Day to operate on

mode

The calendar mode (see table above).

Return Values

The month name for the given Julian Day and mode.



jdtofrench

(PHP 4, PHP 5, PHP 7)

jdtofrenchConverts a Julian Day Count to the French Republican Calendar

Description

jdtofrench ( int $juliandaycount ) : string

Converts a Julian Day Count to the French Republican Calendar.

Parameters

julianday

A julian day number as integer

Return Values

The french revolution date as a string in the form "month/day/year"

See Also

  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



jdtogregorian

(PHP 4, PHP 5, PHP 7)

jdtogregorianConverts Julian Day Count to Gregorian date

Description

jdtogregorian ( int $julianday ) : string

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The gregorian date as a string in the form "month/day/year"

See Also



jdtojewish

(PHP 4, PHP 5, PHP 7)

jdtojewishConverts a Julian day count to a Jewish calendar date

Description

jdtojewish ( int $juliandaycount [, bool $hebrew = FALSE [, int $fl = 0 ]] ) : string

Converts a Julian Day Count to the Jewish Calendar.

Parameters

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, ISO-8859-8 encoded string based, output format.

fl

A bitmask which may consist of CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM and CAL_JEWISH_ADD_GERESHAYIM.

Return Values

The Jewish date as a string in the form "month/day/year", or an ISO-8859-8 encoded Hebrew date string, according to the hebrew parameter.

Examples

Example #1 jdtojewish() Example

<?php
$jd 
gregoriantojd(1082002);
echo 
jdtojewish($jdtrue), PHP_EOL,
     
jdtojewish($jdtrueCAL_JEWISH_ADD_GERESHAYIM), PHP_EOL,
     
jdtojewish($jdtrueCAL_JEWISH_ADD_ALAFIM), PHP_EOL,
     
jdtojewish($jdtrue,CAL_JEWISH_ADD_ALAFIM_GERESH), PHP_EOL;
?>

The above example will output:

   ב חשון התשסג
   ב' חשון התשס"ג
   ב חשון ה אלפים תשסג
   ב חשון ה'תשסג
   

See Also

  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



jdtojulian

(PHP 4, PHP 5, PHP 7)

jdtojulianConverts a Julian Day Count to a Julian Calendar Date

Description

jdtojulian ( int $julianday ) : string

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parameters

julianday

A julian day number as integer

Return Values

The julian date as a string in the form "month/day/year"

See Also

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



jdtounix

(PHP 4, PHP 5, PHP 7)

jdtounixConvert Julian Day to Unix timestamp

Description

jdtounix ( int $jday ) : int

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is UTC.

Parameters

jday

A julian day number between 2440588 and 2465342.

Return Values

The unix timestamp for the start (midnight, not noon) of the given Julian day.

See Also

  • unixtojd() - Convert Unix timestamp to Julian Day



jewishtojd

(PHP 4, PHP 5, PHP 7)

jewishtojdConverts a date in the Jewish Calendar to Julian Day Count

Description

jewishtojd ( int $month , int $day , int $year ) : int

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

Parameters

month

The month as a number from 1 to 13, where 1 means Tishri, 13 means Elul, and 6 and 7 mean Adar in regular years, but Adar I and Adar II, respectively, in leap years.

day

The day as a number from 1 to 30. If the month has only 29 days, the first day of the following month is assumed.

year

The year as a number between 1 and 9999

Return Values

The julian day for the given jewish date as an integer.

See Also

  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



juliantojd

(PHP 4, PHP 5, PHP 7)

juliantojdConverts a Julian Calendar date to Julian Day Count

Description

juliantojd ( int $month , int $day , int $year ) : int

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

Parameters

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

Return Values

The julian day for the given julian date as an integer.

See Also

  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



unixtojd

(PHP 4, PHP 5, PHP 7)

unixtojdConvert Unix timestamp to Julian Day

Description

unixtojd ([ int $timestamp = time() ] ) : int

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given. Either way, the time is regarded as local time (not UTC).

Parameters

timestamp

A unix timestamp to convert.

Return Values

A julian day number as integer.

See Also

  • jdtounix() - Convert Julian Day to Unix timestamp


Table of Contents

  • cal_days_in_month — Return the number of days in a month for a given year and calendar
  • cal_from_jd — Converts from Julian Day Count to a supported calendar
  • cal_info — Returns information about a particular calendar
  • cal_to_jd — Converts from a supported calendar to Julian Day Count
  • easter_date — Get Unix timestamp for midnight on Easter of a given year
  • easter_days — Get number of days after March 21 on which Easter falls for a given year
  • frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd — Converts a Gregorian date to Julian Day Count
  • jddayofweek — Returns the day of the week
  • jdmonthname — Returns a month name
  • jdtofrench — Converts a Julian Day Count to the French Republican Calendar
  • jdtogregorian — Converts Julian Day Count to Gregorian date
  • jdtojewish — Converts a Julian day count to a Jewish calendar date
  • jdtojulian — Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix — Convert Julian Day to Unix timestamp
  • jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count
  • juliantojd — Converts a Julian Calendar date to Julian Day Count
  • unixtojd — Convert Unix timestamp to Julian Day



Date and Time


Introduction

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.

Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = $date->modify('+7 days') and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Note: The timezones referenced in this section can be found in the List of Supported Timezones.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

There is no installation needed to use these functions; they are part of the PHP core.

Note: Getting the latest timezone database

The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: Experimental DateTime support in PHP 5.1.x

Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Date/Time Configuration Options
Name Default Changeable Changelog
date.default_latitude "31.7667" PHP_INI_ALL  
date.default_longitude "35.2333" PHP_INI_ALL  
date.sunrise_zenith "90.583333" PHP_INI_ALL  
date.sunset_zenith "90.583333" PHP_INI_ALL  
date.timezone "" PHP_INI_ALL Available as of PHP 5.1.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

date.default_latitude float

The default latitude.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions. Prior to PHP 5.4.0, this would only work if the TZ environment variable was not set. The precedence order for which timezone is used if none is explicitly mentioned is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.

Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().



Resource Types

This extension has no resource types defined.




Predefined Constants

The DATE_ constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)


Examples

Table of Contents


Date/Time Arithmetic

The following examples show some pitfalls of Date/Time arithmetic with regard to DST transitions and months having different numbers of days.

Example #1 DateTimeImmutable::add/sub add intervals which cover elapsed time

Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).

<?php
$dt 
= new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->add(new DateInterval("PT3H"));
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

The above example will output:

   Start: 2015-11-01 00:00:00 -04:00
   End:   2015-11-01 02:00:00 -05:00
   

Example #2 DateTimeImmutable::modify and strtotime increment or decrement individual component values

Adding +24 hours over a DST transition will add exactly 24 hours as seen in the date/time string (unless the start or end time is on a transition point).

<?php
$dt 
= new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->modify("+24 hours");
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

The above example will output:

   Start: 2015-11-01 00:00:00 -04:00
   End:   2015-11-02 00:00:00 -05:00
   

Example #3 Adding or subtracting times can over- or underflow dates

Like where January 31st + 1 month will result in March 2nd (leap year) or 3rd (normal year).

<?php
echo "Normal year:\n"// February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->modify("+1 month");
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo 
"Leap year:\n"// February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->modify("+1 month");
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

The above example will output:

   Normal year:
   Start: 2015-01-31 00:00:00 -05:00
   End:   2015-03-03 00:00:00 -05:00
   Leap year:
   Start: 2016-01-31 00:00:00 -05:00
   End:   2016-03-02 00:00:00 -05:00
   

To get the last day of the next month (i.e. to prevent the overflow), the last day of format is available as of PHP 5.3.0.

<?php
echo "Normal year:\n"// February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->modify("last day of next month");
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo 
"Leap year:\n"// February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo 
"Start: "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt $dt->modify("last day of next month");
echo 
"End:   "$dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

The above example will output:

   Normal year:
   Start: 2015-01-31 00:00:00 -05:00
   End:   2015-02-28 00:00:00 -05:00
   Leap year:
   Start: 2016-01-31 00:00:00 -05:00
   End:   2016-02-29 00:00:00 -05:00
   




The DateTime class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.

Class synopsis

DateTime implements DateTimeInterface {
/* Inherited constants */
const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T" ;
const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" ;
const string DateTimeInterface::RFC822 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T" ;
const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \G\M\T" ;
const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string DateTimeInterface::RSS = "D, d M Y H:i:s O" ;
const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public __construct ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] )
public add ( DateInterval $interval ) : DateTime
public static createFromFormat ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTime
public static createFromImmutable ( DateTimeImmutable $object ) : DateTime
public static getLastErrors ( void ) : array
public modify ( string $modifier ) : DateTime
public static __set_state ( array $array ) : DateTime
public setDate ( int $year , int $month , int $day ) : DateTime
public setISODate ( int $year , int $week [, int $dayOfWeek = 1 ] ) : DateTime
public setTime ( int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTime
public setTimestamp ( int $timestamp ) : DateTime
public setTimezone ( DateTimeZone $timezone ) : DateTime
public sub ( DateInterval $interval ) : DateTime
public diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

Changelog

Version Description
7.2.0 The class constants of DateTime are now defined on DateTimeInterface.
7.0.0 Added constants: DATE_RFC3339_EXTENDED and DateTime::RFC3339_EXTENDED.
5.5.0 The class now implements DateTimeInterface.
5.4.24 The COOKIE constant was changed to reflect RFC 1036 using a four digit year rather than a two digit year (RFC 850) as prior versions.
5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).


DateTime::add

date_add

(PHP 5 >= 5.3.0, PHP 7)

DateTime::add -- date_add Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Description

Object oriented style

public DateTime::add ( DateInterval $interval ) : DateTime

Procedural style

date_add ( DateTime $object , DateInterval $interval ) : DateTime

Adds the specified DateInterval object to the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

interval

A DateInterval object

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::add() example

Object oriented style

<?php
$date 
= new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo 
$date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date 
date_create('2000-01-01');
date_add($datedate_interval_create_from_date_string('10 days'));
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2000-01-11
   

Example #2 Further DateTime::add() examples

<?php
$date 
= new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

   2000-01-01 10:00:30
   2007-06-05 04:03:02
   

Example #3 Beware when adding months

<?php
$date 
= new DateTime('2000-12-31');
$interval = new DateInterval('P1M');

$date->add($interval);
echo 
$date->format('Y-m-d') . "\n";

$date->add($interval);
echo 
$date->format('Y-m-d') . "\n";
?>

The above example will output:

   2001-01-31
   2001-03-03
   

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also



DateTime::__construct

date_create

(PHP 5 >= 5.2.0, PHP 7)

DateTime::__construct -- date_createReturns new DateTime object

Description

Object oriented style

public DateTime::__construct ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

date_create ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTime

Returns new DateTime object.

Parameters

datetime

A date/time string. Valid formats are explained in Date and Time Formats.

Enter "now" here to obtain the current time when using the $timezone parameter.

timezone

A DateTimeZone object representing the timezone of $datetime.

If $timezone is omitted, the current timezone will be used.

Note:

The $timezone parameter and the current timezone are ignored when the $datetime parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Return Values

Returns a new DateTime instance. Procedural style returns FALSE on failure.

Errors/Exceptions

Emits Exception in case of an error.

Changelog

Version Description
7.1 From now on microseconds are filled with actual value. Not with '00000'.
5.3.0 If datetime contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.

Examples

Example #1 DateTime::__construct() example

Object oriented style

<?php
try {
    
$date = new DateTime('2000-01-01');
} catch (
Exception $e) {
    echo 
$e->getMessage();
    exit(
1);
}

echo 
$date->format('Y-m-d');
?>

Procedural style

<?php
$date 
date_create('2000-01-01');
if (!
$date) {
    
$e date_get_last_errors();
    foreach (
$e['errors'] as $error) {
        echo 
"$error\n";
    }
    exit(
1);
}

echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2000-01-01
   

Example #2 Intricacies of DateTime::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo 
$date->format('Y-m-d H:i:sP') . "\n";
?>

The above example will output something similar to:

   2000-01-01 00:00:00-05:00
   2000-01-01 00:00:00+12:00
   2010-04-24 10:24:16-04:00
   2010-04-25 02:24:16+12:00
   2000-01-01 00:00:00+00:00
   2000-03-01 00:00:00-05:00
   

See Also



DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

DateTime::createFromFormat -- date_create_from_formatParses a time string according to a specified format

Description

Object oriented style

public static DateTime::createFromFormat ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTime

Procedural style

date_create_from_format ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTime

Returns a new DateTime object representing the date and time specified by the datetime string, which was formatted in the given format.

Parameters

format

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

The following characters are recognized in the format parameter string
format character Description Example parsable values
Day --- ---
d and j Day of the month, 2 digits with or without leading zeros 01 to 31 or 1 to 31
D and l A textual representation of a day Mon through Sun or Sunday through Saturday
S English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. st, nd, rd or th.
z The day of the year (starting from 0) 0 through 365
Month --- ---
F and M A textual representation of a month, such as January or Sept January through December or Jan through Dec
m and n Numeric representation of a month, with or without leading zeros 01 through 12 or 1 through 12
Year --- ---
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively)
Time --- ---
a and A Ante meridiem and Post meridiem am or pm
g and h 12-hour format of an hour with or without leading zero 1 through 12 or 01 through 12
G and H 24-hour format of an hour with or without leading zeros 0 through 23 or 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
v Milliseconds (up to three digits) Example: 12, 345
u Microseconds (up to six digits) Example: 45, 654321
Timezone --- ---
e, O, P and T Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT
Full Date/Time --- ---
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Example: 1292177455
Whitespace and Separators --- ---
(space) One space or one tab Example:
# One of the following separation symbol: ;, :, /, ., ,, -, ( or ) Example: /
;, :, /, ., ,, -, ( or ) The specified character. Example: -
? A random byte Example: ^ (Be aware that for UTF-8 characters you might need more than one ?. In this case, using * is probably what you want instead)
* Random bytes until the next separator or digit Example: * in Y-*-d with the string 2009-aWord-08 will match aWord
! Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch Without !, all fields will be set to the current date and time.
| Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch if they have not been parsed yet Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0.
+ If this format specifier is present, trailing data in the string will not cause an error, but a warning instead Use DateTime::getLastErrors() to find out whether trailing data was present.

Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTime::getLastErrors().

To include literal characters in format, you have to escape them with a backslash (\).

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

datetime

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

If timezone is omitted and datetime contains no timezone, the current timezone will be used.

Note:

The timezone parameter and the current timezone are ignored when the datetime parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Return Values

Returns a new DateTime instance or FALSE on failure.

Changelog

Version Description
7.3.0 The v format specifier has been added.
5.3.9 The + format specifier has been added.

Examples

Example #1 DateTime::createFromFormat() example

Object oriented style

<?php
$date 
DateTime::createFromFormat('j-M-Y''15-Feb-2009');
echo 
$date->format('Y-m-d');
?>

Procedural style

<?php
$date 
date_create_from_format('j-M-Y''15-Feb-2009');
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2009-02-15
   

Example #2 Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' date('Y-m-d H:i:s') . "\n";

$format 'Y-m-d';
$date DateTime::createFromFormat($format'2009-02-15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-!d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format '!d';
$date DateTime::createFromFormat($format'15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

   Current time: 2010-04-23 10:29:35
   Format: Y-m-d; 2009-02-15 10:29:35
   Format: Y-m-d H:i:s; 2009-02-15 15:16:17
   Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
   Format: !d; 1970-01-15 00:00:00
   

Example #3 Format string with literal characters

<?php
echo DateTime::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>

The above example will output something similar to:

   23:15:03
   

See Also



DateTime::createFromImmutable

(PHP 7 >= 7.3.0)

DateTime::createFromImmutableReturns new DateTime object encapsulating the given DateTimeImmutable object

Description

public static DateTime::createFromImmutable ( DateTimeImmutable $object ) : DateTime

Parameters

object

The immutable DateTimeImmutable object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime object is created containing the same date, time, and timezone information.

Examples

Example #1 Creating a mutable date time object

<?php
$date 
= new DateTimeImmutable("2014-06-20 11:45 Europe/London");

$mutable DateTime::createFromImmutable$date );
?>

Return Values

Returns a new DateTime instance.



DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getLastErrors -- date_get_last_errorsReturns the warnings and errors

Description

Object oriented style

public static DateTime::getLastErrors ( void ) : array

Procedural style

date_get_last_errors ( void ) : array

Returns an array of warnings and errors found while parsing a date/time string.

Parameters

This function has no parameters.

Return Values

Returns array containing info about warnings and errors.

Examples

Example #1 DateTime::getLastErrors() example

Object oriented style

<?php
try {
    
$date = new DateTime('asdfasdf');
} catch (
Exception $e) {
    
// For demonstration purposes only...
    
print_r(DateTime::getLastErrors());

    
// The real object oriented way to do this is
    // echo $e->getMessage();
}
?>

Procedural style

<?php
$date 
date_create('asdfasdf');
print_r(date_get_last_errors());
?>

The above examples will output:

   Array
   (
      [warning_count] => 1
      [warnings] => Array
          (
              [6] => Double timezone specification
          )
   
      [error_count] => 1
      [errors] => Array
          (
              [0] => The timezone could not be found in the database
          )
   
   )
   

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.



DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7)

DateTime::modify -- date_modifyAlters the timestamp

Description

Object oriented style

public DateTime::modify ( string $modifier ) : DateTime

Procedural style

date_modify ( DateTime $object , string $modifier ) : DateTime

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by DateTimeImmutable::__construct().

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modifier

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version Description
5.3.6 Absolute date/time statements now take effect. Previously, only relative parts were used.
5.3.0Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::modify() example

Object oriented style

<?php
$date 
= new DateTime('2006-12-12');
$date->modify('+1 day');
echo 
$date->format('Y-m-d');
?>

Procedural style

<?php
$date 
date_create('2006-12-12');
date_modify($date'+1 day');
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2006-12-13
   

Example #2 Beware when adding or subtracting months

<?php
$date 
= new DateTime('2000-12-31');

$date->modify('+1 month');
echo 
$date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo 
$date->format('Y-m-d') . "\n";
?>

The above example will output:

   2001-01-31
   2001-03-03
   

See Also



DateTime::__set_state

(PHP 5 >= 5.3.0, PHP 7)

DateTime::__set_stateThe __set_state handler

Description

public static DateTime::__set_state ( array $array ) : DateTime

The __set_state() handler.

Parameters

array

Initialization array.

Return Values

Returns a new instance of a DateTime object.



DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setDate -- date_date_setSets the date

Description

Object oriented style

public DateTime::setDate ( int $year , int $month , int $day ) : DateTime

Procedural style

date_date_set ( DateTime $object , int $year , int $month , int $day ) : DateTime

Resets the current date of the DateTime object to a different date.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version Description
5.3.0Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setDate() example

Object oriented style

<?php
$date 
= new DateTime();
$date->setDate(200123);
echo 
$date->format('Y-m-d');
?>

Procedural style

<?php
$date 
date_create();
date_date_set($date200123);
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2001-02-03
   

Example #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime();

$date->setDate(2001228);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001229);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001143);
echo 
$date->format('Y-m-d') . "\n";
?>

The above example will output:

   2001-02-28
   2001-03-01
   2002-02-03
   

See Also



DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setISODate -- date_isodate_setSets the ISO date

Description

Object oriented style

public DateTime::setISODate ( int $year , int $week [, int $dayOfWeek = 1 ] ) : DateTime

Procedural style

date_isodate_set ( DateTime $object , int $year , int $week [, int $dayOfWeek = 1 ] ) : DateTime

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

year

Year of the date.

week

Week of the date.

dayOfWeek

Offset from the first day of the week.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version Description
5.3.0Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setISODate() example

Object oriented style

<?php
$date 
= new DateTime();

$date->setISODate(20082);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(200827);
echo 
$date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date 
date_create();

date_isodate_set($date20082);
echo 
date_format($date'Y-m-d') . "\n";

date_isodate_set($date200827);
echo 
date_format($date'Y-m-d') . "\n";
?>

The above examples will output:

   2008-01-07
   2008-01-13
   

Example #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime();

$date->setISODate(200827);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(200828);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(2008537);
echo 
$date->format('Y-m-d') . "\n";
?>

The above example will output:

   2008-01-13
   2008-01-14
   2009-01-04
   

Example #3 Finding the month a week is in

<?php
$date 
= new DateTime();
$date->setISODate(200814);
echo 
$date->format('n');
?>

The above examples will output:

   3
   

See Also



DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setTime -- date_time_setSets the time

Description

Object oriented style

public DateTime::setTime ( int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTime

Procedural style

date_time_set ( DateTime $object , int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTime

Resets the current time of the DateTime object to a different time.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

microsecond

Microsecond of the time.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version Description
7.1.0 The microsecond parameter was added.
5.3.0Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setTime() example

Object oriented style

<?php
$date 
= new DateTime('2001-01-01');

$date->setTime(1455);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(145524);
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date 
date_create('2001-01-01');

date_time_set($date1455);
echo 
date_format($date'Y-m-d H:i:s') . "\n";

date_time_set($date145524);
echo 
date_format($date'Y-m-d H:i:s') . "\n";
?>

The above examples will output something similar to:

   2001-01-01 14:55:00
   2001-01-01 14:55:24
   

Example #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime('2001-01-01');

$date->setTime(145524);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(145565);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(146524);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(255524);
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

   2001-01-01 14:55:24
   2001-01-01 14:56:05
   2001-01-01 15:05:24
   2001-01-02 01:55:24
   

See Also



DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7)

DateTime::setTimestamp -- date_timestamp_setSets the date and time based on an Unix timestamp

Description

Object oriented style

public DateTime::setTimestamp ( int $timestamp ) : DateTime

Procedural style

date_timestamp_set ( DateTime $object , int $timestamp ) : DateTime

Sets the date and time based on an Unix timestamp.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

timestamp

Unix timestamp representing the date.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::setTimestamp() example

Object oriented style

<?php
$date 
= new DateTime();
echo 
$date->format('U = Y-m-d H:i:s') . "\n";

$date->setTimestamp(1171502725);
echo 
$date->format('U = Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date 
date_create();
echo 
date_format($date'U = Y-m-d H:i:s') . "\n";

date_timestamp_set($date1171502725);
echo 
date_format($date'U = Y-m-d H:i:s') . "\n";
?>

The above examples will output something similar to:

   1272508903 = 2010-04-28 22:41:43
   1171502725 = 2007-02-14 20:25:25
   

Notes

Using the Unix timestamp format to construct a new DateTime object is an alternative when using PHP 5.2, as shown in the example below.

Example #2 DateTime::setTimestamp() alternative in PHP 5.2

<?php
$ts 
1171502725;
$date = new DateTime("@$ts");
echo 
$date->format('U = Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

   1171502725 = 2007-02-14 20:25:25
   

See Also



DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setTimezone -- date_timezone_setSets the time zone for the DateTime object

Description

Object oriented style

public DateTime::setTimezone ( DateTimeZone $timezone ) : DateTime

Procedural style

date_timezone_set ( DateTime $object , DateTimeZone $timezone ) : DateTime

Sets a new timezone for a DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

timezone

A DateTimeZone object representing the desired time zone.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version Description
5.3.0Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setTimeZone() example

Object oriented style

<?php
$date 
= new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";
?>

Procedural style

<?php
$date 
date_create('2000-01-01'timezone_open('Pacific/Nauru'));
echo 
date_format($date'Y-m-d H:i:sP') . "\n";

date_timezone_set($datetimezone_open('Pacific/Chatham'));
echo 
date_format($date'Y-m-d H:i:sP') . "\n";
?>

The above examples will output:

   2000-01-01 00:00:00+12:00
   2000-01-01 01:45:00+13:45
   

See Also



DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7)

DateTime::sub -- date_sub Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Description

Object oriented style

public DateTime::sub ( DateInterval $interval ) : DateTime

Procedural style

date_sub ( DateTime $object , DateInterval $interval ) : DateTime

Subtracts the specified DateInterval object from the specified DateTime object.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

interval

A DateInterval object

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::sub() example

Object oriented style

<?php
$date 
= new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo 
$date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date 
date_create('2000-01-20');
date_sub($datedate_interval_create_from_date_string('10 days'));
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

   2000-01-10
   

Example #2 Further DateTime::sub() examples

<?php
$date 
= new DateTime('2000-01-20');
$date->sub(new DateInterval('PT10H30S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output:

   2000-01-19 13:59:30
   1992-08-15 19:56:58
   

Example #3 Beware when subtracting months

<?php
$date 
= new DateTime('2001-04-30');
$interval = new DateInterval('P1M');

$date->sub($interval);
echo 
$date->format('Y-m-d') . "\n";

$date->sub($interval);
echo 
$date->format('Y-m-d') . "\n";
?>

The above example will output:

   2001-03-30
   2001-03-02
   

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also


Table of Contents



The DateTimeImmutable class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

Representation of date and time.

Class synopsis

DateTimeImmutable implements DateTimeInterface {
/* Inherited constants */
const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T" ;
const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" ;
const string DateTimeInterface::RFC822 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T" ;
const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \G\M\T" ;
const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string DateTimeInterface::RSS = "D, d M Y H:i:s O" ;
const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public __construct ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] )
public add ( DateInterval $interval ) : DateTimeImmutable
public static createFromFormat ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTimeImmutable
public static createFromMutable ( DateTime $object ) : DateTimeImmutable
public static getLastErrors ( void ) : array
public modify ( string $modifier ) : DateTimeImmutable
public static __set_state ( array $array ) : DateTimeImmutable
public setDate ( int $year , int $month , int $day ) : DateTimeImmutable
public setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTimeImmutable
public setTime ( int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTimeImmutable
public setTimestamp ( int $timestamp ) : DateTimeImmutable
public sub ( DateInterval $interval ) : DateTimeImmutable
public diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

DateTimeImmutable::add

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::add Adds an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable::add ( DateInterval $interval ) : DateTimeImmutable

Like DateTime::add() but works with DateTimeImmutable.



DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__construct -- date_create_immutableReturns new DateTimeImmutable object

Description

Object oriented style

public DateTimeImmutable::__construct ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

date_create_immutable ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTimeImmutable

Like DateTime::__construct() but works with DateTimeImmutable.



DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::createFromFormat -- date_create_immutable_from_formatParses a time string according to a specified format

Description

Object oriented style

public static DateTimeImmutable::createFromFormat ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTimeImmutable

Procedural style

date_create_immutable_from_format ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTimeImmutable

Like DateTime::createFromFormat() but works with DateTimeImmutable.



DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7)

DateTimeImmutable::createFromMutableReturns new DateTimeImmutable object encapsulating the given DateTime object

Description

public static DateTimeImmutable::createFromMutable ( DateTime $object ) : DateTimeImmutable

Parameters

object

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.

Examples

Example #1 Creating an immutable date time object

<?php
$date 
= new DateTime("2014-06-20 11:45 Europe/London");

$immutable DateTimeImmutable::createFromMutable$date );
?>

Return Values

Returns a new DateTimeImmutable instance.



DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::getLastErrorsReturns the warnings and errors

Description

public static DateTimeImmutable::getLastErrors ( void ) : array

Like DateTime::getLastErrors() but works with DateTimeImmutable.



DateTimeImmutable::modify

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::modifyCreates a new object with modified timestamp

Description

public DateTimeImmutable::modify ( string $modifier ) : DateTimeImmutable

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modifier

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the newly created object or FALSE on failure.



DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__set_stateThe __set_state handler

Description

public static DateTimeImmutable::__set_state ( array $array ) : DateTimeImmutable

Like DateTime::__set_state() but works with DateTimeImmutable.



DateTimeImmutable::setDate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setDateSets the date

Description

public DateTimeImmutable::setDate ( int $year , int $month , int $day ) : DateTimeImmutable

Like DateTime::setDate() but works with DateTimeImmutable.



DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setISODateSets the ISO date

Description

public DateTimeImmutable::setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTimeImmutable

Like DateTime::setISODate() but works with DateTimeImmutable.



DateTimeImmutable::setTime

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimeSets the time

Description

public DateTimeImmutable::setTime ( int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTimeImmutable

Like DateTime::setTime() but works with DateTimeImmutable.



DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimestampSets the date and time based on a Unix timestamp

Description

public DateTimeImmutable::setTimestamp ( int $timestamp ) : DateTimeImmutable

Like DateTime::setTimestamp() but works with DateTimeImmutable.



DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimezoneSets the time zone

Description

public DateTimeImmutable::setTimezone ( DateTimeZone $timezone ) : DateTimeImmutable

Like DateTime::setTimezone() but works with DateTimeImmutable.



DateTimeImmutable::sub

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::sub Subtracts an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable::sub ( DateInterval $interval ) : DateTimeImmutable

Like DateTime::sub() but works with DateTimeImmutable.


Table of Contents



The DateTimeInterface interface

(PHP 5 >= 5.5.0, PHP 7)

Introduction

DateTimeInterface is meant so that both DateTime and DateTimeImmutable can be type hinted for. It is not possible to implement this interface with userland classes.

Class synopsis

DateTimeInterface {
/* Constants */
const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC7231 = "D, d M Y H:i:s \G\M\T" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

Predefined Constants

DateTimeInterface::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTimeInterface::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC)
DateTimeInterface::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)

Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use DateTime::ATOM or DATE_ATOM for compatibility with ISO-8601 instead.

DateTimeInterface::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTimeInterface::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTimeInterface::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTimeInterface::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::RFC7231
DATE_RFC7231
RFC 7231 (since PHP 7.0.19 and 7.1.5) (example: Sat, 30 Apr 2016 17:52:13 GMT)
DateTimeInterface::RFC2822
DATE_RFC2822
RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTimeInterface::RFC3339_EXTENDED
DATE_RFC3339_EXTENDED
RFC 3339 EXTENDED format (since PHP 7.0.0) (example: 2005-08-15T15:52:01.000+00:00)
DateTimeInterface::RSS
DATE_RSS
RSS (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Changelog

Version Description
7.2.0 The class constants of DateTime are now defined on DateTimeInterface.
5.5.8 Trying to implement DateTimeInterface raises a fatal error now. Formerly implementing the interface didn't raise an error, but the behavior was erroneous.


DateTime::diff

DateTimeImmutable::diff

DateTimeInterface::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7)

DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diffReturns the difference between two DateTime objects

Description

Object oriented style

public DateTime::diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
public DateTimeImmutable::diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
public DateTimeInterface::diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval

Procedural style

date_diff ( DateTimeInterface $originObject , DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval

Returns the difference between two DateTimeInterface objects.

Parameters

datetime

The date to compare to.

absolute

Should the interval be forced to be positive?

Return Values

The DateInterval object represents the difference between the two dates or FALSE on failure.

The return value more specifically represents the interval to apply to the original object ($this or $originObject) to arrive at the $targetObject. This process is not always reversible.

Examples

Example #1 DateTime::diff() example

Object oriented style

<?php
$origin 
= new DateTime('2009-10-11');
$target = new DateTime('2009-10-13');
$interval $origin->diff($target);
echo 
$interval->format('%R%a days');
?>

Procedural style

<?php
$origin 
date_create('2009-10-11');
$target date_create('2009-10-13');
$interval date_diff($origin$target);
echo 
$interval->format('%R%a days');
?>

The above examples will output:

   +2 days
   

Example #2 DateTime object comparison

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

<?php
$date1 
= new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 $date2);
var_dump($date1 $date2);
?>

The above example will output:

   bool(false)
   bool(true)
   bool(false)
   

See Also

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object


DateTime::format

DateTimeImmutable::format

DateTimeInterface::format

date_format

(PHP 5 >= 5.2.1, PHP 7)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_formatReturns date formatted according to given format

Description

Object oriented style

public DateTime::format ( string $format ) : string
public DateTimeImmutable::format ( string $format ) : string
public DateTimeInterface::format ( string $format ) : string

Procedural style

date_format ( DateTimeInterface $object , string $format ) : string

Returns date formatted according to given format.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

format

The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string 'D, d M Y H:i:s'.

The following characters are recognized in the format parameter string
format character Description Example returned values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
W ISO-8601 week number of year, weeks starting on Monday Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
u Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321
v Milliseconds (added in PHP 7.0.0). Same note applies as for u. Example: 654
Timezone --- ---
e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00
T Timezone abbreviation Examples: EST, MDT ...
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time --- ---
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().

Note:

Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

Return Values

Returns the formatted date string on success or FALSE on failure.

Examples

Example #1 DateTime::format() example

Object oriented style

<?php
$date 
= new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:s');
?>

Procedural style

<?php
$date 
date_create('2000-01-01');
echo 
date_format($date'Y-m-d H:i:s');
?>

The above example will output:

   2000-01-01 00:00:00
   

Notes

This method does not use locales. All output is in English.

See Also

  • date() - Format a local time/date


DateTime::getOffset

DateTimeImmutable::getOffset

DateTimeInterface::getOffset

date_offset_get

(PHP 5 >= 5.2.1, PHP 7)

DateTime::getOffset -- DateTimeImmutable::getOffset -- DateTimeInterface::getOffset -- date_offset_getReturns the timezone offset

Description

Object oriented style

public DateTime::getOffset ( void ) : int
public DateTimeImmutable::getOffset ( void ) : int
public DateTimeInterface::getOffset ( void ) : int

Procedural style

Returns the timezone offset.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns the timezone offset in seconds from UTC on success or FALSE on failure.

Examples

Example #1 DateTime::getOffset() example

Object oriented style

<?php
$winter 
= new DateTime('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTime('2008-06-21', new DateTimeZone('America/New_York'));

echo 
$winter->getOffset() . "\n";
echo 
$summer->getOffset() . "\n";
?>

Procedural style

<?php
$winter 
date_create('2010-12-21'timezone_open('America/New_York'));
$summer date_create('2008-06-21'timezone_open('America/New_York'));

echo 
date_offset_get($winter) . "\n";
echo 
date_offset_get($summer) . "\n";
?>

The above examples will output:

   -18000
   -14400
   

Note: -18000 = -5 hours, -14400 = -4 hours.



DateTime::getTimestamp

DateTimeImmutable::getTimestamp

DateTimeInterface::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTimeInterface::getTimestamp -- date_timestamp_getGets the Unix timestamp

Description

Object oriented style

public DateTime::getTimestamp ( void ) : int
public DateTimeImmutable::getTimestamp ( void ) : int
public DateTimeInterface::getTimestamp ( void ) : int

Procedural style

Gets the Unix timestamp.

Parameters

This function has no parameters.

Return Values

Returns the Unix timestamp representing the date.

Examples

Example #1 DateTime::getTimestamp() example

Object oriented style

<?php
$date 
= new DateTime();
echo 
$date->getTimestamp();
?>

Procedural style

<?php
$date 
date_create();
echo 
date_timestamp_get($date);
?>

The above examples will output something similar to:

   1272509157
   

Notes

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

See Also



DateTime::getTimezone

DateTimeImmutable::getTimezone

DateTimeInterface::getTimezone

date_timezone_get

(PHP 5 >= 5.2.1, PHP 7)

DateTime::getTimezone -- DateTimeImmutable::getTimezone -- DateTimeInterface::getTimezone -- date_timezone_getReturn time zone relative to given DateTime

Description

Object oriented style

public DateTime::getTimezone ( void ) : DateTimeZone
public DateTimeImmutable::getTimezone ( void ) : DateTimeZone
public DateTimeInterface::getTimezone ( void ) : DateTimeZone

Procedural style

Return time zone relative to given DateTime.

Parameters

object

Procedural style only: A DateTime object returned by date_create()

Return Values

Returns a DateTimeZone object on success or FALSE on failure.

Examples

Example #1 DateTime::getTimezone() example

Object oriented style

<?php
$date 
= new DateTime(null, new DateTimeZone('Europe/London'));
$tz $date->getTimezone();
echo 
$tz->getName();
?>

Procedural style

<?php
$date 
date_create(nulltimezone_open('Europe/London'));
$tz date_timezone_get($date);
echo 
timezone_name_get($tz);
?>

The above examples will output:

   Europe/London
   

See Also



DateTime::__wakeup

DateTimeImmutable::__wakeup

DateTimeInterface::__wakeup

(PHP 5 >= 5.3.0, PHP 7)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeupThe __wakeup handler

Description

public DateTime::__wakeup ( void )
public DateTimeImmutable::__wakeup ( void )
public DateTimeInterface::__wakeup ( void )

The __wakeup() handler.

Parameters

This function has no parameters.

Return Values

Initializes a DateTime object.


Table of Contents



The DateTimeZone class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

Representation of time zone.

Class synopsis

DateTimeZone {
/* Constants */
const integer AFRICA = 1 ;
const integer AMERICA = 2 ;
const integer ANTARCTICA = 4 ;
const integer ARCTIC = 8 ;
const integer ASIA = 16 ;
const integer ATLANTIC = 32 ;
const integer AUSTRALIA = 64 ;
const integer EUROPE = 128 ;
const integer INDIAN = 256 ;
const integer PACIFIC = 512 ;
const integer UTC = 1024 ;
const integer ALL = 2047 ;
const integer ALL_WITH_BC = 4095 ;
const integer PER_COUNTRY = 4096 ;
/* Methods */
public __construct ( string $timezone )
public getLocation ( void ) : array
public getName ( void ) : string
public getOffset ( DateTimeInterface $datetime ) : int
public getTransitions ([ int $timestampBegin = PHP_INT_MIN [, int $timestampEnd = PHP_INT_MAX ]] ) : array
public static listAbbreviations ( void ) : array
public static listIdentifiers ([ int $timezoneGroup = DateTimeZone::ALL [, string $countryCode = NULL ]] ) : array
}

Predefined Constants

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Arctic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.


DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::__construct -- timezone_openCreates new DateTimeZone object

Description

Object oriented style

public DateTimeZone::__construct ( string $timezone )

Procedural style

timezone_open ( string $timezone ) : DateTimeZone

Creates new DateTimeZone object.

Parameters

timezone

One of the supported timezone names or an offset value (+0200).

Return Values

Returns DateTimeZone on success. Procedural style returns FALSE on failure.

Errors/Exceptions

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Changelog

Version Description
5.5.10 The timezone parameter accepts offset values.

Examples

Example #1 Catching errors when instantiating DateTimeZone

<?php
// Error handling by catching exceptions
$timezones = array('Europe/London''Mars/Phobos''Jupiter/Europa');

foreach (
$timezones as $tz) {
    try {
        
$mars = new DateTimeZone($tz);
    } catch(
Exception $e) {
        echo 
$e->getMessage() . '<br />';
    }
}
?>

The above example will output:

   DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
   DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)
   



DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7)

DateTimeZone::getLocation -- timezone_location_getReturns location information for a timezone

Description

Object oriented style

public DateTimeZone::getLocation ( void ) : array

Procedural style

timezone_location_get ( DateTimeZone $object ) : array

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

Return Values

Array containing location information about timezone or FALSE on failure.

Examples

Example #1 DateTimeZone::getLocation() example

<?php
$tz 
= new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>

The above example will output:

   Array
   (
       [country_code] => CZ
       [latitude] => 50.08333
       [longitude] => 14.43333
       [comments] => 
   )
   Array
   (
       [country_code] => CZ
       [latitude] => 50.08333
       [longitude] => 14.43333
       [comments] => 
   )
   



DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::getName -- timezone_name_getReturns the name of the timezone

Description

Object oriented style

public DateTimeZone::getName ( void ) : string

Procedural style

timezone_name_get ( DateTimeZone $object ) : string

Returns the name of the timezone.

Parameters

object

The DateTimeZone for which to get a name.

Return Values

One of the timezone names in the list of timezones.



DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::getOffset -- timezone_offset_getReturns the timezone offset from GMT

Description

Object oriented style

public DateTimeZone::getOffset ( DateTimeInterface $datetime ) : int

Procedural style

timezone_offset_get ( DateTimeZone $object , DateTimeInterface $datetime ) : int

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

datetime

DateTime that contains the date/time to compute the offset from.

Return Values

Returns time zone offset in seconds on success or FALSE on failure.

Changelog

Version Description
5.5.19, 5.6.3 datetime type changed to DateTimeInterface. Previously, DateTime.

Examples

Example #1 DateTimeZone::getOffset() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now"$dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now"$dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>



DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::getTransitions -- timezone_transitions_getReturns all transitions for the timezone

Description

Object oriented style

public DateTimeZone::getTransitions ([ int $timestampBegin = PHP_INT_MIN [, int $timestampEnd = PHP_INT_MAX ]] ) : array

Procedural style

timezone_transitions_get ( DateTimeZone $object [, int $timestampBegin = PHP_INT_MIN [, int $timestampEnd = PHP_INT_MAX ]] ) : array

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

timestampBegin

Begin timestamp.

timestampEnd

End timestamp.

Return Values

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Changelog

Version Description
5.3.0 The optional timestampBegin and timestampEnd were added.

Examples

Example #1 A timezone_transitions_get() example

<?php
$timezone 
= new DateTimeZone("Europe/London");
$transitions $timezone->getTransitions();
print_r(array_slice($transitions03));
?>

The above example will output something similar to:

   Array
   (
       [0] => Array
           (
               [ts] => -9223372036854775808
               [time] => -292277022657-01-27T08:29:52+0000
               [offset] => 3600
               [isdst] => 1
               [abbr] => BST
           )
   
       [1] => Array
           (
               [ts] => -1691964000
               [time] => 1916-05-21T02:00:00+0000
               [offset] => 3600
               [isdst] => 1
               [abbr] => BST
           )
   
       [2] => Array
           (
               [ts] => -1680472800
               [time] => 1916-10-01T02:00:00+0000
               [offset] => 0
               [isdst] => 
               [abbr] => GMT
           )
   
   )
   



DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::listAbbreviations -- timezone_abbreviations_listReturns associative array containing dst, offset and the timezone name

Description

Object oriented style

public static DateTimeZone::listAbbreviations ( void ) : array

Procedural style

timezone_abbreviations_list ( void ) : array

Note:

The data for this function are precompiled for performance reasons, and are not updated when using a newer » timezonedb.

Return Values

Returns array on success or FALSE on failure.

Examples

Example #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations 
DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

The above example will output something similar to:

   Array
   (
       [0] => Array
           (
               [dst] => 1
               [offset] => -14400
               [timezone_id] => America/Porto_Acre
           )
   
       [1] => Array
           (
               [dst] => 1
               [offset] => -14400
               [timezone_id] => America/Eirunepe
           )
   
       [2] => Array
           (
               [dst] => 1
               [offset] => -14400
               [timezone_id] => America/Rio_Branco
           )
   
       [3] => Array
           (
               [dst] => 1
               [offset] => -14400
               [timezone_id] => Brazil/Acre
           )
   
   )
   

See Also



DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::listIdentifiers -- timezone_identifiers_listReturns a numerically indexed array containing all defined timezone identifiers

Description

Object oriented style

public static DateTimeZone::listIdentifiers ([ int $timezoneGroup = DateTimeZone::ALL [, string $countryCode = NULL ]] ) : array

Procedural style

timezone_identifiers_list ([ int $timezoneGroup = DateTimeZone::ALL [, string $countryCode = NULL ]] ) : array

Parameters

timezoneGroup

One of the DateTimeZone class constants (or a combination).

countryCode

A two-letter ISO 3166-1 compatible country code.

Note: This option is only used when timezoneGroup is set to DateTimeZone::PER_COUNTRY.

Return Values

Returns array on success or FALSE on failure.

Changelog

Version Description
5.3.0 Added the optional timezoneGroup and countryCode parameters.

Examples

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers 
DateTimeZone::listIdentifiers();
for (
$i=0$i 5$i++) {
    echo 
"$timezone_identifiers[$i]\n";
}
?>

The above example will output something similar to:

   Africa/Abidjan
   Africa/Accra
   Africa/Addis_Ababa
   Africa/Algiers
   Africa/Asmara
   

See Also


Table of Contents



The DateInterval class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

Represents a date interval.

A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime's constructor supports.

More specifically, the information in an object of the DateInterval class is an instruction to get from one date/time to another date/time. This process is not always reversible.

A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff().

Class synopsis

DateInterval {
/* Properties */
public integer y ;
public integer m ;
public integer d ;
public integer h ;
public integer i ;
public integer s ;
public float f ;
public integer invert ;
public mixed days ;
/* Methods */
public __construct ( string $duration )
public static createFromDateString ( string $datetime ) : DateInterval
public format ( string $format ) : string
}

Properties

y

Number of years.

m

Number of months.

d

Number of days.

h

Number of hours.

i

Number of minutes.

s

Number of seconds.

f

Number of microseconds, as a fraction of a second.

invert

Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().

days

If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

Before PHP 5.4.20/5.5.4 instead of FALSE you will receive -99999 upon accessing the property.

Changelog

Version Description
7.1.0 The f property was added.


DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::__constructCreates a new DateInterval object

Description

public DateInterval::__construct ( string $duration )

Creates a new DateInterval object.

Parameters

duration

An interval specification.

The format starts with the letter P, for period. Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

duration Period Designators
Period Designator Description
Y years
M months
D days
W weeks. These get converted into days, so can not be combined with D.
H hours
M minutes
S seconds

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

Note:

The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g. 25 hours is invalid).

These formats are based on the » ISO 8601 duration specification.

Errors/Exceptions

Throws an Exception when the duration cannot be parsed as an interval.

Examples

Example #1 DateInterval example

<?php

$interval 
= new DateInterval('P2Y4DT6H8M');
var_dump($interval);

?>

The above example will output:

   object(DateInterval)#1 (8) {
     ["y"]=>
     int(2)
     ["m"]=>
     int(0)
     ["d"]=>
     int(4)
     ["h"]=>
     int(6)
     ["i"]=>
     int(8)
     ["s"]=>
     int(0)
     ["invert"]=>
     int(0)
     ["days"]=>
     bool(false)
   }
   

See Also



DateInterval::createFromDateString

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::createFromDateStringSets up a DateInterval from the relative parts of the string

Description

public static DateInterval::createFromDateString ( string $datetime ) : DateInterval

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

Parameters

datetime

A date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

Examples

Example #1 Parsing valid date intervals

<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i DateInterval::createFromDateString('1 day');

$i = new DateInterval('P2W');
$i DateInterval::createFromDateString('2 weeks');

$i = new DateInterval('P3M');
$i DateInterval::createFromDateString('3 months');

$i = new DateInterval('P4Y');
$i DateInterval::createFromDateString('4 years');

$i = new DateInterval('P1Y1D');
$i DateInterval::createFromDateString('1 year + 1 day');

$i = new DateInterval('P1DT12H');
$i DateInterval::createFromDateString('1 day + 12 hours');

$i = new DateInterval('PT3600S');
$i DateInterval::createFromDateString('3600 seconds');
?>

Return Values

Returns a new DateInterval instance.



DateInterval::format

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::formatFormats the interval

Description

public DateInterval::format ( string $format ) : string

Formats the interval.

Parameters

format

The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%).
format character Description Example values
% Literal % %
Y Years, numeric, at least 2 digits with leading 0 01, 03
y Years, numeric 1, 3
M Months, numeric, at least 2 digits with leading 0 01, 03, 12
m Months, numeric 1, 3, 12
D Days, numeric, at least 2 digits with leading 0 01, 03, 31
d Days, numeric 1, 3, 31
a Total number of days as a result of a DateTime::diff() or (unknown) otherwise 4, 18, 8123
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23
h Hours, numeric 1, 3, 23
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59
i Minutes, numeric 1, 3, 59
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57
s Seconds, numeric 1, 3, 57
F Microseconds, numeric, at least 6 digits with leading 0 007701, 052738, 428291
f Microseconds, numeric 7701, 52738, 428291
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,

Return Values

Returns the formatted interval.

Notes

Note:

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

Changelog

Version Description
7.1.0 The F and f format characters were added.

Examples

Example #1 DateInterval example

<?php

$interval 
= new DateInterval('P2Y4DT6H8M');
echo 
$interval->format('%d days');

?>

The above example will output:

   4 days
   

Example #2 DateInterval and carry over points

<?php

$interval 
= new DateInterval('P32D');
echo 
$interval->format('%d days');

?>

The above example will output:

   32 days
   

Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers

<?php

$january 
= new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

The above example will output:

   31 total days
   1 month, 0 days
   

See Also


Table of Contents



The DatePeriod class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

Represents a date period.

A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

Class synopsis

DatePeriod implements Traversable {
/* Constants */
const integer EXCLUDE_START_DATE = 1 ;
/* Properties */
public integer recurrences ;
public boolean include_start_date ;
public DateTimeInterface start ;
public DateTimeInterface current ;
public DateTimeInterface end ;
public DateInterval interval ;
/* Methods */
public __construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
public getDateInterval ( void ) : DateInterval
public getEndDate ( void ) : DateTimeInterface
public getRecurrences ( void ) : int
public getStartDate ( void ) : DateTimeInterface
}

Predefined Constants

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Properties

recurrences

The number of recurrences, if the DatePeriod instance had been created by explicitly passing $recurrences. See also DatePeriod::getRecurrences().

include_start_date

Whether to include the start date in the set of recurring dates or not.

start

The start date of the period.

current

During iteration this will contain the current date within the period.

end

The end date of the period.

interval

An ISO 8601 repeating interval specification.

Changelog

Version Description
5.3.27, 5.4.17 The public properties recurrences, include_start_date, start, current, end and interval have been exposed.


DatePeriod::__construct

(PHP 5 >= 5.3.0, PHP 7)

DatePeriod::__constructCreates a new DatePeriod object

Description

public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public DatePeriod::__construct ( string $isostr [, int $options ] )

Creates a new DatePeriod object.

Parameters

start

The start date of the period.

interval

The interval between recurrences within the period.

recurrences

The number of recurrences.

end

The end date of the period.

isostr

An ISO 8601 repeating interval specification.

options

Can be set to DatePeriod::EXCLUDE_START_DATE to exclude the start date from the set of recurring dates within the period.

Changelog

Version Description
5.5.8 end type changed to DateTimeInterface. Previously, DateTime.
5.5.0 start type changed to DateTimeInterface. Previously, DateTime.

Examples

Example #1 DatePeriod example

<?php
$start 
= new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences 4;
$iso 'R4/2012-07-01T00:00:00Z/P7D';

// All of these periods are equivalent.
$period = new DatePeriod($start$interval$recurrences);
$period = new DatePeriod($start$interval$end);
$period = new DatePeriod($iso);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
    echo 
$date->format('Y-m-d')."\n";
}
?>

The above example will output:

   2012-07-01
   2012-07-08
   2012-07-15
   2012-07-22
   2012-07-29
   

Example #2 DatePeriod example with DatePeriod::EXCLUDE_START_DATE

<?php
$start 
= new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');

$period = new DatePeriod($start$interval$end,
                         
DatePeriod::EXCLUDE_START_DATE);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
    echo 
$date->format('Y-m-d')."\n";
}
?>

The above example will output:

   2012-07-08
   2012-07-15
   2012-07-22
   2012-07-29
   

Notes

Unbound numbers of repetitions as specified by ISO 8601 section 4.5 "Recurring time interval" are not supported, i.e. neither passing "R/..." as isostr nor passing NULL as end would work.



DatePeriod::getDateInterval

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getDateInterval Gets the interval

Description

Object oriented style

public DatePeriod::getDateInterval ( void ) : DateInterval

Gets a DateInterval object representing the interval used for the period.

Parameters

This function has no parameters.

Return Values

Returns a DateInterval object

Examples

Example #1 DatePeriod::getDateInterval() example

<?php
$period 
= new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$interval $period->getDateInterval();
echo 
$interval->format('%d day');
?>

The above example will output:

   1 day
   

See Also



DatePeriod::getEndDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getEndDate Gets the end date

Description

Object oriented style

public DatePeriod::getEndDate ( void ) : DateTimeInterface

Gets the end date of the period.

Parameters

This function has no parameters.

Return Values

Returns NULL if the DatePeriod does not have an end date. For example, when initialized with the recurrences parameter, or the isostr parameter without an end date.

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the end parameter.

Returns a DateTime object otherwise.

Examples

Example #1 DatePeriod::getEndDate() example

<?php
$period 
= new DatePeriod(
    new 
DateTime('2016-05-16T00:00:00Z'),
    new 
DateInterval('P1D'),
    new 
DateTime('2016-05-20T00:00:00Z')
);
$start $period->getEndDate();
echo 
$start->format(DateTime::ISO8601);
?>

The above examples will output:

   2016-05-20T00:00:00+0000
   

Example #2 DatePeriod::getEndDate() without an end date

<?php
$period 
= new DatePeriod(
    new 
DateTime('2016-05-16T00:00:00Z'),
    new 
DateInterval('P1D'),
    
7
);
var_dump($period->getEndDate());
?>

The above example will output:

   NULL
   

See Also



DatePeriod::getRecurrences

(PHP 7 >= 7.2.17/7.3.4)

DatePeriod::getRecurrencesGets the number of recurrences

Description

Object oriented style

public DatePeriod::getRecurrences ( void ) : int

Get the number of recurrences.

Parameters

This function has no parameters.

Return Values

Returns the number of recurrences.



DatePeriod::getStartDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getStartDate Gets the start date

Description

Object oriented style

public DatePeriod::getStartDate ( void ) : DateTimeInterface

Gets the start date of the period.

Parameters

This function has no parameters.

Return Values

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the start parameter.

Returns a DateTime object otherwise.

Examples

Example #1 DatePeriod::getStartDate() example

<?php
$period 
= new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$start $period->getStartDate();
echo 
$start->format(DateTime::ISO8601);
?>

The above example will output:

   2016-05-16T00:00:00+0000
   

See Also


Table of Contents



Date/Time Functions


checkdate

(PHP 4, PHP 5, PHP 7)

checkdateValidate a Gregorian date

Description

checkdate ( int $month , int $day , int $year ) : bool

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters

month

The month is between 1 and 12 inclusive.

day

The day is within the allowed number of days for the given month. Leap years are taken into consideration.

year

The year is between 1 and 32767 inclusive.

Return Values

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples

Example #1 checkdate() example

<?php
var_dump
(checkdate(12312000));
var_dump(checkdate(2292001));
?>

The above example will output:

   bool(true)
   bool(false)
   

See Also

  • mktime() - Get Unix timestamp for a date
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp



date_add

(PHP 5 >= 5.3.0, PHP 7)

date_addAlias of DateTime::add()

Description

This function is an alias of: DateTime::add()



date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_create_from_formatAlias of DateTime::createFromFormat()

Description

This function is an alias of: DateTime::createFromFormat()



date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutable_from_formatAlias of DateTimeImmutable::createFromFormat()

Description

This function is an alias of: DateTimeImmutable::createFromFormat()



date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutableAlias of DateTimeImmutable::__construct()

Description

This function is an alias of: DateTimeImmutable::__construct()



date_create

(PHP 5 >= 5.2.0, PHP 7)

date_createAlias of DateTime::__construct()

Description

This function is an alias of: DateTime::__construct()



date_date_set

(PHP 5 >= 5.2.0, PHP 7)

date_date_setAlias of DateTime::setDate()

Description

This function is an alias of: DateTime::setDate()



date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_get Gets the default timezone used by all date/time functions in a script

Description

date_default_timezone_get ( void ) : string

In order of preference, this function returns the default timezone by:

  • Reading the timezone set using the date_default_timezone_set() function (if any)

  • Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.

If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC.

Return Values

Returns a string.

Changelog

Version Description
5.4.0 The TZ environment variable is no longer used to guess the timezone.
5.4.0 The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set
('Europe/London');

if (
date_default_timezone_get()) {
    echo 
'date_default_timezone_set: ' date_default_timezone_get() . '<br />';
}

if (
ini_get('date.timezone')) {
    echo 
'date.timezone: ' ini_get('date.timezone');
}

?>

The above example will output something similar to:

   date_default_timezone_set: Europe/London
   date.timezone: Europe/London
   

Example #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set
('America/Los_Angeles');
echo 
date_default_timezone_get() . ' => ' date('e') . ' => ' date('T');
?>

The above example will output:

   America/Los_Angeles => America/Los_Angeles => PST
   

See Also



date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_set Sets the default timezone used by all date/time functions in a script

Description

date_default_timezone_set ( string $timezoneID ) : bool

date_default_timezone_set() sets the default timezone used by all date/time functions.

Note:

Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

Parameters

timezoneID

The timezone identifier, like UTC, Africa/Lagos, Asia/Hong_Kong, or Europe/Lisbon. The list of valid identifiers is available in the List of Supported Timezones.

Return Values

This function returns FALSE if the timezoneID isn't valid, or TRUE otherwise.

Examples

Example #1 Getting the default timezone

<?php
date_default_timezone_set
('America/Los_Angeles');

$script_tz date_default_timezone_get();

if (
strcmp($script_tzini_get('date.timezone'))){
    echo 
'Script timezone differs from ini-set timezone.';
} else {
    echo 
'Script timezone and ini-set timezone match.';
}
?>

Changelog

Version Description
5.3.0 Now throws E_WARNING rather than E_STRICT.
5.1.2 The function started to validate the timezoneID parameter.

See Also



date_diff

(PHP 5 >= 5.3.0, PHP 7)

date_diffAlias of DateTime::diff()

Description

This function is an alias of: DateTime::diff()



date_format

(PHP 5 >= 5.2.0, PHP 7)

date_formatAlias of DateTime::format()

Description

This function is an alias of: DateTime::format()



date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

date_get_last_errorsAlias of DateTime::getLastErrors()

Description

This function is an alias of: DateTime::getLastErrors()



date_interval_create_from_date_string

(PHP 5 >= 5.3.0, PHP 7)

date_interval_create_from_date_stringAlias of DateInterval::createFromDateString()

Description

This function is an alias of: DateInterval::createFromDateString()



date_interval_format

(PHP 5 >= 5.3.0, PHP 7)

date_interval_formatAlias of DateInterval::format()

Description

This function is an alias of: DateInterval::format()



date_isodate_set

(PHP 5 >= 5.2.0, PHP 7)

date_isodate_setAlias of DateTime::setISODate()

Description

This function is an alias of: DateTime::setISODate()



date_modify

(PHP 5 >= 5.2.0, PHP 7)

date_modifyAlias of DateTime::modify()

Description

This function is an alias of: DateTime::modify()



date_offset_get

(PHP 5 >= 5.2.0, PHP 7)

date_offset_getAlias of DateTime::getOffset()

Description

This function is an alias of: DateTime::getOffset()



date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_parse_from_formatGet info about given date formatted according to the specified format

Description

date_parse_from_format ( string $format , string $datetime ) : array

Returns associative array with detailed info about given date/time.

Parameters

format

Format accepted by DateTime::createFromFormat().

datetime

String representing the date/time.

Return Values

Returns associative array with detailed info about given date/time.

Changelog

Version Description
7.2.0 The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

Examples

Example #1 date_parse_from_format() example

<?php
$date 
"6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP"$date));
?>

The above example will output:

   Array
   (
       [year] => 2009
       [month] => 1
       [day] => 6
       [hour] => 13
       [minute] => 0
       [second] => 0
       [fraction] => 
       [warning_count] => 0
       [warnings] => Array
           (
           )
   
       [error_count] => 0
       [errors] => Array
           (
           )
   
       [is_localtime] => 1
       [zone_type] => 1
       [zone] => 3600
       [is_dst] => 
   )
   

See Also



date_parse

(PHP 5 >= 5.2.0, PHP 7)

date_parseReturns associative array with detailed info about given date/time

Description

date_parse ( string $datetime ) : array

Parameters

datetime

Date/time in format accepted by DateTimeImmutable::__construct().

Return Values

Returns array with information about the parsed date/time on success or FALSE on failure.

Errors/Exceptions

In case the date/time format has an error, the element 'errors' will contains the error messages.

Changelog

Version Description
7.2.0 The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

Examples

Example #1 A date_parse() example

<?php
print_r
(date_parse("2006-12-12 10:00:00.5"));
?>

The above example will output:

   Array
   (
       [year] => 2006
       [month] => 12
       [day] => 12
       [hour] => 10
       [minute] => 0
       [second] => 0
       [fraction] => 0.5
       [warning_count] => 0
       [warnings] => Array()
       [error_count] => 0
       [errors] => Array()
       [is_localtime] => 
   )
   

Relative formats do not influence the values parsed from absolute formats, but are parsed into the "relative" element.

Example #2 date_parse() with relative formats

<?php
print_r
(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));
?>

The above example will output:

   Array
   (
       [year] => 2006
       [month] => 12
       [day] => 12
       [hour] => 10
       [minute] => 0
       [second] => 0
       [fraction] => 0.5
       [warning_count] => 0
       [warnings] => Array
           (
           )
   
       [error_count] => 0
       [errors] => Array
           (
           )
   
       [is_localtime] =>
       [relative] => Array
           (
               [year] => 0
               [month] => 0
               [day] => 7
               [hour] => 1
               [minute] => 0
               [second] => 0
           )
   
   )

See Also



date_sub

(PHP 5 >= 5.3.0, PHP 7)

date_subAlias of DateTime::sub()

Description

This function is an alias of: DateTime::sub()



date_sun_info

(PHP 5 >= 5.1.2, PHP 7)

date_sun_infoReturns an array with information about sunset/sunrise and twilight begin/end

Description

date_sun_info ( int $timestamp , float $latitude , float $longitude ) : array

Parameters

timestamp

Unix timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Return Values

Returns array on success or FALSE on failure. The structure of the array is detailed in the following list:

sunrise
The timestamp of the sunrise (zenith angle = 90°35').
sunset
The timestamp of the sunset (zenith angle = 90°35').
transit
The timestamp when the sun is at its zenith, i.e. has reached its topmost point.
civil_twilight_begin
The start of the civil dawn (zenith angle = 96°). It ends at sunrise.
civil_twilight_end
The end of the civil dusk (zenith angle = 96°). It starts at sunset.
nautical_twilight_begin
The start of the nautical dawn (zenith angle = 102°). It ends at civil_twilight_begin.
nautical_twilight_end
The end of the nautical dusk (zenith angle = 102°). It starts at civil_twilight_end.
astronomical_twilight_begin
The start of the astronomical dawn (zenith angle = 108°). It ends at nautical_twilight_begin.
astronomical_twilight_end
The end of the astronomical dusk (zenith angle = 108°). It starts at nautical_twilight_end.

The values of the array elements are either UNIX timestamps, FALSE if the sun is below the respective zenith for the whole day, or TRUE if the sun is above the respective zenith for the whole day.

Changelog

Version Description
5.2.2 The order of latitude and longitude has been swapped.

Examples

Example #1 A date_sun_info() example

<?php
$sun_info 
date_sun_info(strtotime("2006-12-12"), 31.766735.2333);
foreach (
$sun_info as $key => $val) {
    echo 
"$key: " date("H:i:s"$val) . "\n";
}
?>

The above example will output:

   sunrise: 05:52:11
   sunset: 15:41:21
   transit: 10:46:46
   civil_twilight_begin: 05:24:08
   civil_twilight_end: 16:09:24
   nautical_twilight_begin: 04:52:25
   nautical_twilight_end: 16:41:06
   astronomical_twilight_begin: 04:21:32
   astronomical_twilight_end: 17:12:00
   

Example #2 Polar night

<?php
var_dump
(date_sun_info(strtotime("2017-12-21"), 900));
?>

The above example will output:

   array(9) {
     ["sunrise"]=>
     bool(false)
     ["sunset"]=>
     bool(false)
     ["transit"]=>
     int(1513857490)
     ["civil_twilight_begin"]=>
     bool(false)
     ["civil_twilight_end"]=>
     bool(false)
     ["nautical_twilight_begin"]=>
     bool(false)
     ["nautical_twilight_end"]=>
     bool(false)
     ["astronomical_twilight_begin"]=>
     bool(false)
     ["astronomical_twilight_end"]=>
     bool(false)
   }
   

Example #3 Midnight sun

<?php
var_dump
(date_sun_info(strtotime("2017-06-21"), 900));
?>

The above example will output:

   array(9) {
     ["sunrise"]=>
     bool(true)
     ["sunset"]=>
     bool(true)
     ["transit"]=>
     int(1498046510)
     ["civil_twilight_begin"]=>
     bool(true)
     ["civil_twilight_end"]=>
     bool(true)
     ["nautical_twilight_begin"]=>
     bool(true)
     ["nautical_twilight_end"]=>
     bool(true)
     ["astronomical_twilight_begin"]=>
     bool(true)
     ["astronomical_twilight_end"]=>
     bool(true)
   }
   

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location



date_sunrise

(PHP 5, PHP 7)

date_sunriseReturns time of sunrise for a given day and location

Description

date_sunrise ( int $timestamp [, int $returnFormat = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $utcOffset = 0 ]]]]] ) : mixed

date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location.

Parameters

timestamp

The timestamp of the day from which the sunrise time is taken.

returnFormat

returnFormat constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

zenith is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunrise_zenith
Common zenith angles
Angle Description
90°50' Sunrise: the point where the sun becomes visible.
96° Civil twilight: conventionally used to signify the start of dawn.
102° Nautical twilight: the point at which the horizon starts being visible at sea.
108° Astronomical twilight: the point at which the sun starts being the source of any illumination.

utcOffset

Specified in hours. The utcOffset is ignored, if returnFormat is SUNFUNCS_RET_TIMESTAMP.

Return Values

Returns the sunrise time in a specified returnFormat on success or FALSE on failure. One potential reason for failure is that the sun does not rise at all, which happens inside the polar circles for part of the year.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

The above example will output something similar to:

   Mon Dec 20 2004, sunrise time : 08:54
   

Example #2 No sunrise

<?php
$solstice 
strtotime('2017-12-21');
var_dump(date_sunrise($solsticeSUNFUNCS_RET_STRING69.245833, -53.537222));
?>

The above example will output:

   bool(false)
   

See Also

  • date_sunset() - Returns time of sunset for a given day and location
  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end



date_sunset

(PHP 5, PHP 7)

date_sunset Returns time of sunset for a given day and location

Description

date_sunset ( int $timestamp [, int $returnFormat = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunset_zenith") [, float $utcOffset = 0 ]]]]] ) : mixed

date_sunset() returns the sunset time for a given day (specified as a timestamp) and location.

Parameters

timestamp

The timestamp of the day from which the sunset time is taken.

returnFormat

returnFormat constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

zenith is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunset_zenith
Common zenith angles
Angle Description
90°50' Sunset: the point where the sun becomes invisible.
96° Civil twilight: conventionally used to signify the end of dusk.
102° Nautical twilight: the point at which the horizon ends being visible at sea.
108° Astronomical twilight: the point at which the sun ends being the source of any illumination.

utcOffset

Specified in hours. The utcOffset is ignored, if returnFormat is SUNFUNCS_RET_TIMESTAMP.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Return Values

Returns the sunset time in a specified returnFormat on success or FALSE on failure. One potential reason for failure is that the sun does not set at all, which happens inside the polar circles for part of the year.

Examples

Example #1 date_sunset() example

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

The above example will output something similar to:

   Mon Dec 20 2004, sunset time : 18:13
   

Example #2 No sunset

<?php
$solstice 
strtotime('2017-12-21');
var_dump(date_sunset($solsticeSUNFUNCS_RET_STRING69.245833, -53.537222));
?>

The above example will output:

   bool(false)
   

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end



date_time_set

(PHP 5 >= 5.2.0, PHP 7)

date_time_setAlias of DateTime::setTime()

Description

This function is an alias of: DateTime::setTime()



date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_getAlias of DateTime::getTimestamp()

Description

This function is an alias of: DateTime::getTimestamp()



date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_setAlias of DateTime::setTimestamp()

Description

This function is an alias of: DateTime::setTimestamp()



date_timezone_get

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_getAlias of DateTime::getTimezone()

Description

This function is an alias of: DateTime::getTimezone()



date_timezone_set

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_setAlias of DateTime::setTimezone()

Description

This function is an alias of: DateTime::setTimezone()



date

(PHP 4, PHP 5, PHP 7)

dateFormat a local time/date

Description

date ( string $format [, int $timestamp = time() ] ) : string

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Parameters

format

Format accepted by DateTimeInterface::format().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 date() examples

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

<?php
$tomorrow  
mktime(000date("m")  , date("d")+1date("Y"));
$lastmonth mktime(000date("m")-1date("d"),   date("Y"));
$nextyear  mktime(000date("m"),   date("d"),   date("Y")+1);
?>

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today date("m.d.y");                         // 03.10.01
$today date("j, n, Y");                       // 10, 3, 2001
$today date("Ymd");                           // 20010310
$today date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today date("H:i:s");                         // 17:16:18
$today date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

Notes

Note:

To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also



getdate

(PHP 4, PHP 5, PHP 7)

getdateGet date/time information

Description

getdate ([ int $timestamp = time() ] ) : array

Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an associative array of information related to the timestamp. Elements from the returned associative array are as follows:

Key elements of the returned associative array
Key Description Example returned values
"seconds" Numeric representation of seconds 0 to 59
"minutes" Numeric representation of minutes 0 to 59
"hours" Numeric representation of hours 0 to 23
"mday" Numeric representation of the day of the month 1 to 31
"wday" Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
"mon" Numeric representation of a month 1 through 12
"year" A full numeric representation of a year, 4 digits Examples: 1999 or 2003
"yday" Numeric representation of the day of the year 0 through 365
"weekday" A full textual representation of the day of the week Sunday through Saturday
"month" A full textual representation of a month, such as January or March January through December
0 Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). System Dependent, typically -2147483648 through 2147483647.

Examples

Example #1 getdate() example

<?php
$today 
getdate();
print_r($today);
?>

The above example will output something similar to:

   Array
   (
       [seconds] => 40
       [minutes] => 58
       [hours]   => 21
       [mday]    => 17
       [wday]    => 2
       [mon]     => 6
       [year]    => 2003
       [yday]    => 167
       [weekday] => Tuesday
       [month]   => June
       [0]       => 1055901520
   )
   

See Also



gettimeofday

(PHP 4, PHP 5, PHP 7)

gettimeofdayGet current time

Description

gettimeofday ([ bool $returnFloat = FALSE ] ) : mixed

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

Parameters

returnFloat

When set to TRUE, a float instead of an array is returned.

Return Values

By default an array is returned. If returnFloat is set, then a float is returned.

Array keys:

  • "sec" - seconds since the Unix Epoch
  • "usec" - microseconds
  • "minuteswest" - minutes west of Greenwich
  • "dsttime" - type of dst correction

Changelog

Version Description
5.1.0 The returnFloat parameter was added.

Examples

Example #1 gettimeofday() example

<?php
print_r
(gettimeofday());

echo 
gettimeofday(true);
?>

The above example will output something similar to:

   Array
   (
       [sec] => 1073504408
       [usec] => 238215
       [minuteswest] => 0
       [dsttime] => 1
   )
   
   1073504408.23910
   



gmdate

(PHP 4, PHP 5, PHP 7)

gmdateFormat a GMT/UTC date/time

Description

gmdate ( string $format [, int $timestamp = time() ] ) : string

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

Parameters

format

The format of the outputted date string. See the formatting options for the date() function.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Changelog

Version Description
5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).

Examples

Example #1 gmdate() example

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

<?php
echo date("M d Y H:i:s"mktime(000111998));
echo 
gmdate("M d Y H:i:s"mktime(000111998));
?>

See Also

  • date() - Format a local time/date
  • mktime() - Get Unix timestamp for a date
  • gmmktime() - Get Unix timestamp for a GMT date
  • strftime() - Format a local time/date according to locale settings



gmmktime

(PHP 4, PHP 5, PHP 7)

gmmktimeGet Unix timestamp for a GMT date

Description

gmmktime ([ int $hour = gmdate("H") [, int $minute = gmdate("i") [, int $second = gmdate("s") [, int $month = gmdate("n") [, int $day = gmdate("j") [, int $year = gmdate("Y") [, int $isDST = -1 ]]]]]]] ) : int

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

Parameters

hour

The number of the hour relative to the start of the day determined by month, day and year. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

minute

The number of the minute relative to the start of the hour. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

second

The number of seconds relative to the start of the minute. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

month

The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

day

The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

year

The year

isDST

Parameters always represent a GMT date so isDST doesn't influence the result.

Note:

This parameter has been removed in PHP 7.0.0.

Return Values

Returns a integer Unix timestamp.

Changelog

Version Description
7.0.0 isDST parameter has been removed.
5.1.0 As of PHP 5.1.0, the isDST parameter became deprecated. As a result, the new timezone handling features should be used instead.

Examples

Example #1 gmmktime() basic example

<?php
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"gmmktime(000712000));
?>

See Also

  • mktime() - Get Unix timestamp for a date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp



gmstrftime

(PHP 4, PHP 5, PHP 7)

gmstrftimeFormat a GMT/UTC time/date according to locale settings

Description

gmstrftime ( string $format [, int $timestamp = time() ] ) : string

Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".

Parameters

format

See description in strftime().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale().

Examples

Example #1 gmstrftime() example

<?php
setlocale
(LC_TIME'en_US');
echo 
strftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
echo 
gmstrftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
?>

See Also

  • strftime() - Format a local time/date according to locale settings



idate

(PHP 5, PHP 7)

idateFormat a local time/date as integer

Description

idate ( string $format [, int $timestamp = time() ] ) : int

Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the format parameter.

Parameters

format

The following characters are recognized in the format parameter string
format character Description
B Swatch Beat/Internet Time
d Day of the month
h Hour (12 hour format)
H Hour (24 hour format)
i Minutes
I (uppercase i) returns 1 if DST is activated, 0 otherwise
L (uppercase l) returns 1 for leap year, 0 otherwise
m Month number
s Seconds
t Days in current month
U Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time()
w Day of the week (0 on Sunday)
W ISO-8601 week number of year, weeks starting on Monday
y Year (1 or 2 digits - check note below)
Y Year (4 digits)
z Day of the year
Z Timezone offset in seconds

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 idate() example

<?php
$timestamp 
strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y'$timestamp);
?>

See Also

  • date() - Format a local time/date
  • getdate() - Get date/time information
  • time() - Return current Unix timestamp



localtime

(PHP 4, PHP 5, PHP 7)

localtimeGet the local time

Description

localtime ([ int $timestamp = time() [, bool $associative = FALSE ]] ) : array

The localtime() function returns an array identical to that of the structure returned by the C function call.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

associative

If set to FALSE or not supplied then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds, 0 to 59
  • "tm_min" - minutes, 0 to 59
  • "tm_hour" - hours, 0 to 23
  • "tm_mday" - day of the month, 1 to 31
  • "tm_mon" - month of the year, 0 (Jan) to 11 (Dec)
  • "tm_year" - years since 1900
  • "tm_wday" - day of the week, 0 (Sun) to 6 (Sat)
  • "tm_yday" - day of the year, 0 to 365
  • "tm_isdst" - is daylight savings time in effect? Positive if yes, 0 if not, negative if unknown.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 localtime() example

<?php
$localtime 
localtime();
$localtime_assoc localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

The above example will output something similar to:

   Array
   (
       [0] => 24
       [1] => 3
       [2] => 19
       [3] => 3
       [4] => 3
       [5] => 105
       [6] => 0
       [7] => 92
       [8] => 1
   )
   
   Array
   (
       [tm_sec] => 24
       [tm_min] => 3
       [tm_hour] => 19
       [tm_mday] => 3
       [tm_mon] => 3
       [tm_year] => 105
       [tm_wday] => 0
       [tm_yday] => 92
       [tm_isdst] => 1
   )
   

See Also



microtime

(PHP 4, PHP 5, PHP 7)

microtimeReturn current Unix timestamp with microseconds

Description

microtime ([ bool $getAsFloat = FALSE ] ) : mixed

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

For performance measurements, using hrtime() is recommended.

Parameters

getAsFloat

If used and set to TRUE, microtime() will return a float instead of a string, as described in the return values section below.

Return Values

By default, microtime() returns a string in the form "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds.

If getAsFloat is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Examples

Example #1 Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list(
$usec$sec) = explode(" "microtime());
    return ((float)
$usec + (float)$sec);
}

$time_start microtime_float();

// Sleep for a while
usleep(100);

$time_end microtime_float();
$time $time_end $time_start;

echo 
"Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start 
microtime(true);

// Sleep for a while
usleep(100);

$time_end microtime(true);
$time $time_end $time_start;

echo 
"Did nothing in $time seconds\n";
?>

Example #3 microtime() and REQUEST_TIME_FLOAT (as of PHP 5.4.0)

<?php
// Randomize sleeping time
usleep(mt_rand(10010000));

// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo 
"Did nothing in $time seconds\n";
?>

See Also

  • time() - Return current Unix timestamp
  • hrtime() - Get the system's high resolution time



mktime

(PHP 4, PHP 5, PHP 7)

mktimeGet Unix timestamp for a date

Description

mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $isDST = -1 ]]]]]]] ) : int

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

Notes

Note:

As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.

Parameters

hour

The number of the hour relative to the start of the day determined by month, day and year. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s).

minute

The number of the minute relative to the start of the hour. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s).

second

The number of seconds relative to the start of the minute. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s).

month

The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).

day

The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

year

The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1901 and 2038. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

isDST

This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or isDST is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

Note:

As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Note:

This parameter has been removed in PHP 7.0.0.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
7.0.0 isDST parameter has been removed.
5.3.0 mktime() now throws E_DEPRECATED notice if the isDST parameter is used.
5.1.0 The isDST parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0 When called with no arguments, mktime() throws E_STRICT notice. Use the time() function instead.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c'mktime(123452006));
?>

Example #2 mktime() example

mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".

<?php
echo date("M-d-Y"mktime(00012321997));
echo 
date("M-d-Y"mktime(0001311997));
echo 
date("M-d-Y"mktime(000111998));
echo 
date("M-d-Y"mktime(0001198));
?>

Example #3 Last day of a month

The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".

<?php
$lastday 
mktime(000302000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
$lastday mktime(0004, -312000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

See Also



strftime

(PHP 4, PHP 5, PHP 7)

strftimeFormat a local time/date according to locale settings

Description

strftime ( string $format [, int $timestamp = time() ] ) : string

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to Jan 1, 1970 - will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems, a complete overview of supported conversion specifiers can be found at » MSDN.

Parameters

format

The following characters are recognized in the format parameter string
format Description Example returned values
Day --- ---
%a An abbreviated textual representation of the day Sun through Sat
%A A full textual representation of the day Sunday through Saturday
%d Two-digit day of the month (with leading zeros) 01 to 31
%e Day of the month, with a space preceding single digits. Not implemented as described on Windows. See below for more information. 1 to 31
%j Day of the year, 3 digits with leading zeros 001 to 366
%u ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
%w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
Week --- ---
%U Week number of the given year, starting with the first Sunday as the first week 13 (for the 13th full week of the year)
%V ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week 01 through 53 (where 53 accounts for an overlapping week)
%W A numeric representation of the week of the year, starting with the first Monday as the first week 46 (for the 46th week of the year beginning with a Monday)
Month --- ---
%b Abbreviated month name, based on the locale Jan through Dec
%B Full month name, based on the locale January through December
%h Abbreviated month name, based on the locale (an alias of %b) Jan through Dec
%m Two digit representation of the month 01 (for January) through 12 (for December)
Year --- ---
%C Two digit representation of the century (year divided by 100, truncated to an integer) 19 for the 20th Century
%g Two digit representation of the year going by ISO-8601:1988 standards (see %V) Example: 09 for the week of January 6, 2009
%G The full four-digit version of %g Example: 2008 for the week of January 3, 2009
%y Two digit representation of the year Example: 09 for 2009, 79 for 1979
%Y Four digit representation for the year Example: 2038
Time --- ---
%H Two digit representation of the hour in 24-hour format 00 through 23
%k Hour in 24-hour format, with a space preceding single digits 0 through 23
%I Two digit representation of the hour in 12-hour format 01 through 12
%l (lower-case 'L') Hour in 12-hour format, with a space preceding single digits 1 through 12
%M Two digit representation of the minute 00 through 59
%p UPPER-CASE 'AM' or 'PM' based on the given time Example: AM for 00:31, PM for 22:23
%P lower-case 'am' or 'pm' based on the given time Example: am for 00:31, pm for 22:23
%r Same as "%I:%M:%S %p" Example: 09:34:17 PM for 21:34:17
%R Same as "%H:%M" Example: 00:35 for 12:35 AM, 16:44 for 4:44 PM
%S Two digit representation of the second 00 through 59
%T Same as "%H:%M:%S" Example: 21:34:17 for 09:34:17 PM
%X Preferred time representation based on locale, without the date Example: 03:59:16 or 15:59:16
%z The time zone offset. Not implemented as described on Windows. See below for more information. Example: -0500 for US Eastern Time
%Z The time zone abbreviation. Not implemented as described on Windows. See below for more information. Example: EST for Eastern Time
Time and Date Stamps --- ---
%c Preferred date and time stamp based on locale Example: Tue Feb 5 00:45:10 2009 for February 5, 2009 at 12:45:10 AM
%D Same as "%m/%d/%y" Example: 02/05/09 for February 5, 2009
%F Same as "%Y-%m-%d" (commonly used in database datestamps) Example: 2009-02-05 for February 5, 2009
%s Unix Epoch Time timestamp (same as the time() function) Example: 305815200 for September 10, 1979 08:40:00 AM
%x Preferred date representation based on locale, without the time Example: 02/05/09 for February 5, 2009
Miscellaneous --- ---
%n A newline character ("\n") ---
%t A Tab character ("\t") ---
%% A literal percentage character ("%") ---

Maximum length of this parameter is 1023 characters.

Warning

Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a result, %u may not function as described in this manual.

Warning

Windows only:

The %e modifier is not supported in the Windows implementation of this function. To achieve this value, the %#d modifier can be used instead. The example below illustrates how to write a cross platform compatible function.

The %z and %Z modifiers both return the time zone name instead of the offset or abbreviation.

Warning

macOS only: The %P modifier is not supported in the macOS implementation of this function.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a string formatted according format using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 E_WARNING messages and return FALSE. On other operating systems you may not get any E_WARNING messages and the output may contain the conversion specifiers unconverted.

Changelog

Version Description
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

This example will work if you have the respective locales installed in your system.

Example #1 strftime() locale examples

<?php
setlocale
(LC_TIME"C");
echo 
strftime("%A");
setlocale(LC_TIME"fi_FI");
echo 
strftime(" in Finnish is %A,");
setlocale(LC_TIME"fr_FR");
echo 
strftime(" in French %A and");
setlocale(LC_TIME"de_DE");
echo 
strftime(" in German %A.\n");
?>

Example #2 ISO 8601:1988 week number example

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Example #3 Cross platform compatible example using the %e modifier

<?php

// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format '%%e%%%e%%';

// Check for Windows to find and replace the %e 
// modifier correctly
if (strtoupper(substr(PHP_OS03)) == 'WIN') {
    
$format preg_replace('#(?<!%)((?:%%)*)%e#''\1%#d'$format);
}

echo 
strftime($format);
?>

Example #4 Display all known and unknown formats.

<?php
// Describe the formats.
$strftimeFormats = array(
    
'A' => 'A full textual representation of the day',
    
'B' => 'Full month name, based on the locale',
    
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
    
'D' => 'Same as "%m/%d/%y"',
    
'E' => '',
    
'F' => 'Same as "%Y-%m-%d"',
    
'G' => 'The full four-digit version of %g',
    
'H' => 'Two digit representation of the hour in 24-hour format',
    
'I' => 'Two digit representation of the hour in 12-hour format',
    
'J' => '',
    
'K' => '',
    
'L' => '',
    
'M' => 'Two digit representation of the minute',
    
'N' => '',
    
'O' => '',
    
'P' => 'lower-case "am" or "pm" based on the given time',
    
'Q' => '',
    
'R' => 'Same as "%H:%M"',
    
'S' => 'Two digit representation of the second',
    
'T' => 'Same as "%H:%M:%S"',
    
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
    
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
    
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
    
'X' => 'Preferred time representation based on locale, without the date',
    
'Y' => 'Four digit representation for the year',
    
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
    
'a' => 'An abbreviated textual representation of the day',
    
'b' => 'Abbreviated month name, based on the locale',
    
'c' => 'Preferred date and time stamp based on local',
    
'd' => 'Two-digit day of the month (with leading zeros)',
    
'e' => 'Day of the month, with a space preceding single digits',
    
'f' => '',
    
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
    
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
    
'i' => '',
    
'j' => 'Day of the year, 3 digits with leading zeros',
    
'k' => 'Hour in 24-hour format, with a space preceding single digits',
    
'l' => 'Hour in 12-hour format, with a space preceding single digits',
    
'm' => 'Two digit representation of the month',
    
'n' => 'A newline character ("\n")',
    
'o' => '',
    
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
    
'q' => '',
    
'r' => 'Same as "%I:%M:%S %p"',
    
's' => 'Unix Epoch Time timestamp',
    
't' => 'A Tab character ("\t")',
    
'u' => 'ISO-8601 numeric representation of the day of the week',
    
'v' => '',
    
'w' => 'Numeric representation of the day of the week',
    
'x' => 'Preferred date representation based on locale, without the time',
    
'y' => 'Two digit representation of the year',
    
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
    
'%' => 'A literal percentage character ("%")',
);

// Results.
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
    if (
False !== ($value = @strftime("%{$format}"))){
        
$strftimeValues[$format] = $value;
    }
}

// Find the longest value.
$maxValueLength max(array_map('strlen'$strftimeValues));

// Report known formats.
foreach($strftimeValues as $format => $value){
    echo 
"Known format   : '{$format}' = "str_pad("'{$value}'"$maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats.
foreach(array_diff_key($strftimeFormats$strftimeValues) as $format => $description){
    echo 
"Unknown format : '{$format}'   "str_pad(' '$maxValueLength), ($description " ( {$description} )" ''), "\n";
}
?>

The above example will output something similar to:

   Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
   Known format   : 'B' = 'December'          ( Full month name, based on the locale )
   Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
   Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
   Known format   : 'M' = '24'                ( Two digit representation of the minute )
   Known format   : 'S' = '44'                ( Two digit representation of the second )
   Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
   Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
   Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
   Known format   : 'Y' = '2010'              ( Four digit representation for the year )
   Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
   Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
   Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
   Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
   Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
   Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
   Known format   : 'm' = '12'                ( Two digit representation of the month )
   Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
   Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
   Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
   Known format   : 'y' = '10'                ( Two digit representation of the year )
   Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
   Known format   : '%' = '%'                 ( A literal percentage character ("%") )
   Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
   Unknown format : 'D'                       ( Same as "%m/%d/%y" )
   Unknown format : 'E'
   Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
   Unknown format : 'G'                       ( The full four-digit version of %g )
   Unknown format : 'J'
   Unknown format : 'K'
   Unknown format : 'L'
   Unknown format : 'N'
   Unknown format : 'O'
   Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
   Unknown format : 'Q'
   Unknown format : 'R'                       ( Same as "%H:%M" )
   Unknown format : 'T'                       ( Same as "%H:%M:%S" )
   Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
   Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
   Unknown format : 'f'
   Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
   Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
   Unknown format : 'i'
   Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
   Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
   Unknown format : 'n'                       ( A newline character ("\n") )
   Unknown format : 'o'
   Unknown format : 'q'
   Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
   Unknown format : 's'                       ( Unix Epoch Time timestamp )
   Unknown format : 't'                       ( A Tab character ("\t") )
   Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
   Unknown format : 'v'
   

Notes

Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.

See Also



strptime

(PHP 5 >= 5.1.0, PHP 7)

strptime Parse a time/date generated with strftime()

Description

strptime ( string $date , string $format ) : array

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

Parameters

date (string)

The string to parse (e.g. returned from strftime()).

format (string)

The format used in date (e.g. the same as used in strftime()). Note that some of the format options available to strftime() may not have any effect within strptime(); the exact subset that are supported will vary based on the operating system and C library in use.

For more information about the format options, read the strftime() page.

Return Values

Returns an array or FALSE on failure.

The following parameters are returned in the array
parameters Description
"tm_sec" Seconds after the minute (0-61)
"tm_min" Minutes after the hour (0-59)
"tm_hour" Hour since midnight (0-23)
"tm_mday" Day of the month (1-31)
"tm_mon" Months since January (0-11)
"tm_year" Years since 1900
"tm_wday" Days since Sunday (0-6)
"tm_yday" Days since January 1 (0-365)
"unparsed" the date part which was not recognized using the specified format

Examples

Example #1 strptime() example

<?php
$format 
'%d/%m/%Y %H:%M:%S';
$strf strftime($format);

echo 
"$strf\n";

print_r(strptime($strf$format));
?>

The above example will output something similar to:

   03/10/2004 15:54:19
   
   Array
   (
       [tm_sec] => 19
       [tm_min] => 54
       [tm_hour] => 15
       [tm_mday] => 3
       [tm_mon] => 9
       [tm_year] => 104
       [tm_wday] => 0
       [tm_yday] => 276
       [unparsed] =>
   )
   

Notes

Note: This function is not implemented on Windows platforms.

Note:

Internally, this function calls the strptime() function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended on PHP 5.3.0 and later.

Note:

"tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

Note:

Prior to PHP 5.2.0, this function could return undefined behaviour. Notably, the "tm_sec", "tm_min" and "tm_hour" entries would return undefined values.

See Also



strtotime

(PHP 4, PHP 5, PHP 7)

strtotimeParse about any English textual datetime description into a Unix timestamp

Description

strtotime ( string $datetime [, int $now = time() ] ) : int

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

Warning

The Unix timestamp that this function returns does not contain information about time zones. In order to do calculations with date/time information, you should use the more capable DateTimeImmutable.

Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See date_default_timezone_get() on the various ways to define the default time zone.

Parameters

datetime

A date/time string. Valid formats are explained in Date and Time Formats.

now

The timestamp which is used as a base for the calculation of relative dates.

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.3.0 Prior to PHP 5.3.0, relative time formats supplied to the datetime argument of strtotime() such as this week, previous week, last week, and next week were interpreted to mean a 7 day period relative to the current date/time, rather than a week period of Monday through Sunday.
5.3.0 Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime() returned FALSE.
5.2.7 In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.1.0 Now returns FALSE on failure, instead of -1.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

5.0.2 In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.0 Microseconds began to be allowed, but they are ignored.

Examples

Example #1 A strtotime() example

<?php
echo strtotime("now"), "\n";
echo 
strtotime("10 September 2000"), "\n";
echo 
strtotime("+1 day"), "\n";
echo 
strtotime("+1 week"), "\n";
echo 
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo 
strtotime("next Thursday"), "\n";
echo 
strtotime("last Monday"), "\n";
?>

Example #2 Checking for failure

<?php
$str 
'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>

Notes

Note:

If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

Note:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

Prior to PHP 5.1.0, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems.

For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

See Also



time

(PHP 4, PHP 5, PHP 7)

timeReturn current Unix timestamp

Description

time ( void ) : int

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Examples

Example #1 time() example

<?php
$nextWeek 
time() + (24 60 60);
                   
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now:       'date('Y-m-d') ."\n";
echo 
'Next Week: 'date('Y-m-d'$nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: 'date('Y-m-d'strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

   Now:       2005-03-30
   Next Week: 2005-04-06
   Next Week: 2005-04-06
   

Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • date() - Format a local time/date
  • microtime() - Return current Unix timestamp with microseconds



timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_abbreviations_listAlias of DateTimeZone::listAbbreviations()

Description

This function is an alias of: DateTimeZone::listAbbreviations()



timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_identifiers_listAlias of DateTimeZone::listIdentifiers()

Description

This function is an alias of: DateTimeZone::listIdentifiers()



timezone_location_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_location_getAlias of DateTimeZone::getLocation()

Description

This function is an alias of: DateTimeZone::getLocation()



timezone_name_from_abbr

(PHP 5 >= 5.1.3, PHP 7)

timezone_name_from_abbrReturns the timezone name from abbreviation

Description

timezone_name_from_abbr ( string $abbr [, int $utcOffset = -1 [, int $isDST = -1 ]] ) : string

Parameters

abbr

Time zone abbreviation.

utcOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isDST

Daylight saving time indicator. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the utcOffset is assumed to be an offset with daylight saving in effect; if 0, then utcOffset is assumed to be an offset without daylight saving in effect. If abbr doesn't exist then the time zone is searched solely by the utcOffset and isDST.

Return Values

Returns time zone name on success or FALSE on failure.

Examples

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo 
timezone_name_from_abbr(""36000) . "\n";
?>

The above example will output something similar to:

   Europe/Berlin
   Europe/Paris
   

See Also



timezone_name_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_name_getAlias of DateTimeZone::getName()

Description

This function is an alias of: DateTimeZone::getName()



timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_offset_getAlias of DateTimeZone::getOffset()

Description

This function is an alias of: DateTimeZone::getOffset()



timezone_open

(PHP 5 >= 5.2.0, PHP 7)

timezone_openAlias of DateTimeZone::__construct()

Description

This function is an alias of: DateTimeZone::__construct()



timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_transitions_getAlias of DateTimeZone::getTransitions()

Description

This function is an alias of: DateTimeZone::getTransitions()



timezone_version_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_version_get Gets the version of the timezonedb

Description

timezone_version_get ( void ) : string

Returns the current version of the timezonedb.

Return Values

Returns a string.

Examples

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

The above example will output something similar to:

   2009.7
   


Table of Contents



Supported Date and Time Formats

Table of Contents

This section describes all the different formats that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands. The formats are grouped by section. In most cases formats from different sections, separated by whitespace, comma or dot, can be used in the same date/time string. For each of the supported formats, one or more examples are given, as well as a description for the format. Characters in single quotes in the formats are case-insensitive ('t' could be t or T), characters in double quotes are case-sensitive ("T" is only T).


Time Formats

This page describes the different date/time formats that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.

Used Symbols
Description Formats Examples
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "07", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
MM [0-5][0-9] "00", "12", "59"
II [0-5][0-9] "00", "12", "59"
space [ \t]  
tz "("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ "CEST", "Europe/Amsterdam", "America/Indiana/Knox"
tzcorrection "GMT"? [+-] hh ":"? MM? "+0400", "GMT-07:00", "-07:00"
12 Hour Notation
Description Format Examples
Hour only, with meridian hh space? meridian "4 am", "5PM"
Hour and minutes, with meridian hh [.:] MM space? meridian "4:08 am", "7:19P.M."
Hour, minutes and seconds, with meridian hh [.:] MM [.:] II space? meridian "4:08:37 am", "7:19:19P.M."
MS SQL (Hour, minutes, seconds and fraction with meridian), PHP 5.3 and later only hh ":" MM ":" II [.:] [0-9]+ meridian "4:08:39:12313am"
24 Hour Notation
Description Format Examples
Hour and minutes 't'? HH [.:] MM "04:08", "19.19", "T23:43"
Hour and minutes, no colon 't'? HH MM "0408", "t1919", "T2343"
Hour, minutes and seconds 't'? HH [.:] MM [.:] II "04.08.37", "t19:19:19"
Hour, minutes and seconds, no colon 't'? HH MM II "040837", "T191919"
Hour, minutes, seconds and timezone 't'? HH [.:] MM [.:] II space? ( tzcorrection | tz ) "040837CEST", "T191919-0700"
Hour, minutes, seconds and fraction 't'? HH [.:] MM [.:] II frac "04.08.37.81412", "19:19:19.532453"
Time zone information tz | tzcorrection "CEST", "Europe/Amsterdam", "+0430", "GMT-06:00"


Date Formats

This page describes the different date formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description Format Examples
daysuf "st" | "nd" | "rd" | "th"  
dd ([0-2]?[0-9] | "3"[01]) daysuf? "7th", "22nd", "31"
DD "0" [0-9] | [1-2][0-9] | "3" [01] "07", "31"
m 'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII"  
M 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec'  
mm "0"? [0-9] | "1"[0-2] "0", "04", "7", "12"
MM "0" [0-9] | "1"[0-2] "00", "04", "07", "12"
y [0-9]{1,4} "00", "78", "08", "8", "2008"
yy [0-9]{2} "00", "08", "78"
YY [0-9]{4} "2000", "2008", "1978"
Localized Notations
Description Format Examples
American month and day mm "/" dd "5/12", "10/27"
American month, day and year mm "/" dd "/" y "12/22/78", "1/17/2006", "1/17/6"
Four digit year, month and day with slashes YY "/" mm "/" dd "2008/6/30", "1978/12/22"
Four digit year and month (GNU) YY "-" mm "2008-6", "2008-06", "1978-12"
Year, month and day with dashes y "-" mm "-" dd "2008-6-30", "78-12-22", "8-6-21"
Day, month and four digit year, with dots, tabs or dashes dd [.\t-] mm [.-] YY "30-6-2008", "22.12.1978"
Day, month and two digit year, with dots or tabs dd [.\t] mm "." yy "30.6.08", "22\t12.78"
Day, textual month and year dd ([ \t.-])* m ([ \t.-])* y "30-June 2008", "22DEC78", "14 III 1879"
Textual month and four digit year (Day reset to 1) m ([ \t.-])* YY "June 2008", "DEC1978", "March 1879"
Four digit year and textual month (Day reset to 1) YY ([ \t.-])* m "2008 June", "1978-XII", "1879.MArCH"
Textual month, day and year m ([ .\t-])* dd [,.stndrh\t ]+ y "July 1st, 2008", "April 17, 1790", "May.9,78"
Textual month and day m ([ .\t-])* dd [,.stndrh\t ]* "July 1st,", "Apr 17", "May.9"
Day and textual month d ([ .\t-])* m "1 July", "17 Apr", "9.May"
Month abbreviation, day and year M "-" DD "-" y "May-09-78", "Apr-17-1790"
Year, month abbreviation and day y "-" M "-" DD "78-Dec-22", "1814-MAY-17"
Year (and just the year) YY "1978", "2008"
Textual month (and just the month) m "March", "jun", "DEC"
ISO8601 Notations
Description Format Examples
Eight digit year, month and day YY MM DD "15810726", "19780417", "18140517"
Four digit year, month and day with slashes YY "/" MM "/" DD "2008/06/30", "1978/12/22"
Two digit year, month and day with dashes yy "-" MM "-" DD "08-06-30", "78-12-22"
Four digit year with optional sign, month and day [+-]? YY "-" MM "-" DD "-0002-07-26", "+1978-04-17", "1814-05-17"

Note:

For the y and yy formats, years below 100 are handled in a special way when the y or yy symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".

Note:

The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has precedence.

Note:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

Note:

It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

Note that as of PHP 5.1.0 the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.

It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".

If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).



Compound Formats

This page describes the different compound date/time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description Formats Examples
DD "0" [0-9] | [1-2][0-9] | "3" [01] "02", "12", "31"
doy "00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] "001", "012", "180", "350", "366"
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "07", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
ii [0-5][0-9] "04", "8", "59"
II [0-5][0-9] "04", "08", "59"
M 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec'  
MM [0-1][0-9] "00", "12"
space [ \t]  
ss [0-5][0-9] "04", "8", "59"
SS [0-5][0-9] "04", "08", "59"
W "0"[1-9] | [1-4][0-9] | "5"[0-3] "05", "17", "53"
tzcorrection "GMT"? [+-] hh ":"? II? "+0400", "GMT-07:00", "-07:00"
YY [0-9]{4} "2000", "2008", "1978"
Localized Notations
Description Format Examples
Common Log Format dd "/" M "/" YY : HH ":" II ":" SS space tzcorrection "10/Oct/2000:13:55:36 -0700"
EXIF YY ":" MM ":" DD " " HH ":" II ":" SS "2008:08:07 18:11:31"
ISO year with ISO week YY "-"? "W" W "2008W27", "2008-W28"
ISO year with ISO week and day YY "-"? "W" W "-"? [0-7] "2008W273", "2008-W28-3"
MySQL YY "-" MM "-" DD " " HH ":" II ":" SS "2008-08-07 18:11:31"
PostgreSQL: Year with day-of-year YY "."? doy "2008.197", "2008197"
SOAP YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection? "2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"
Unix Timestamp "@" "-"? [0-9]+ "@1215282385"
XMLRPC YY MM DD "T" hh ":" II ":" SS "20080701T22:38:07", "20080701T9:38:07"
XMLRPC (Compact) YY MM DD 't' hh II SS "20080701t223807", "20080701T093807"
WDDX YY "-" mm "-" dd "T" hh ":" ii ":" ss "2008-7-1T9:3:37"

Note:

The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

The "Unix Timestamp" format sets the timezone to UTC.



Relative Formats

This page describes the different relative date/time formats that the strtotime(), DateTime and date_create() parser understands.

Used Symbols
Description Format
dayname 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
daytext 'weekday' | 'weekdays'
number [+-]?[0-9]+
ordinal 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this'
reltext 'next' | 'last' | 'previous' | 'this'
space [ \t]+
unit (('sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' | 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' | daytext
Day-based Notations
Format Description Examples
'yesterday' Midnight of yesterday "yesterday 14:00"
'midnight' The time is set to 00:00:00  
'today' The time is set to 00:00:00  
'now' Now - this is simply ignored  
'noon' The time is set to 12:00:00 "yesterday noon"
'tomorrow' Midnight of tomorrow  
'back of' hour 15 minutes past the specified hour "back of 7pm", "back of 15"
'front of' hour 15 minutes before the specified hour "front of 5am", "front of 23"
'first day of' Sets the day of the first of the current month. This phrase is best used together with a month name following it. "first day of January 2008"
'last day of' Sets the day to the last day of the current month. This phrase is best used together with a month name following it. "last day of next month"
ordinal space dayname space 'of' Calculates the x-th week day of the current month. "first sat of July 2008"
'last' space dayname space 'of' Calculates the last week day of the current month. "last sat of July 2008"
number space? (unit | 'week') Handles relative time items where the value is a number. "+5 weeks", "12 day", "-7 weekdays"
ordinal space unit Handles relative time items where the value is text. "fifth day", "second month"
'ago' Negates all the values of previously found relative time items. "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago"
dayname Moves to the next day of this name. "Monday"
reltext space 'week' Handles the special format "weekday + last/this/next week". "Monday next week"

Note:

Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.

Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.

Note:

Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.

  1. "dayname" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").
  2. "number dayname" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").
  3. "number week dayname" will first add the number of weeks, but does not advance to another day. In this case "number week" and "dayname" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").
  4. "ordinal dayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
  5. "number week ordinal dayname" will first add the number of weeks, and then advances to another day. In this case "number week" and "ordinal dayname" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").
  6. "ordinal dayname 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

  1. It sets the day-of-month to 1.
  2. "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
  3. "ordinal dayname " does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).
  4. "'last' dayname 'of' " takes the last dayname of the current month. (Example: "last wed of july 2008" means "2008-07-30")
  5. "'last' dayname" takes the last dayname from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

Note:

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

Note:

number is an integer number; if a decimal number is given, the dot (or comma) is likely interpreted as delimiter. For instance, '+1.5 hours' is parsed like '+1 5 hours', not as '+1 hour +30 minutes'.

Changelog

Version Description
5.6.23, 7.0.8 Weeks always start on monday. Formerly, sunday would also be considered to start a week.
5.3.3 "first day" and "last day" changed to behave has "+1 day" and "-1 day", respectively. Previously, the behaviour was as "first day of" and "last day of".




List of Supported Timezones

Table of Contents

Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set().

Caution

The behavior of timezones not listed here is undefined.

Note: The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: This list is based upon the timezone database version 2020.1.


Africa

Africa
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers
Africa/Asmara Africa/Bamako Africa/Bangui Africa/Banjul
Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura
Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry
Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti Africa/Douala
Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare
Africa/Johannesburg Africa/Juba Africa/Kampala Africa/Khartoum
Africa/Kigali Africa/Kinshasa Africa/Lagos Africa/Libreville
Africa/Lome Africa/Luanda Africa/Lubumbashi Africa/Lusaka
Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane
Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena
Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo
Africa/Sao_Tome Africa/Tripoli Africa/Tunis Africa/Windhoek


America

America
America/Adak America/Anchorage America/Anguilla America/Antigua
America/Araguaina America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/Cordoba
America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos
America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman
America/Argentina/Ushuaia America/Aruba America/Asuncion America/Atikokan
America/Bahia America/Bahia_Banderas America/Barbados America/Belem
America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota
America/Boise America/Cambridge_Bay America/Campo_Grande America/Cancun
America/Caracas America/Cayenne America/Cayman America/Chicago
America/Chihuahua America/Costa_Rica America/Creston America/Cuiaba
America/Curacao America/Danmarkshavn America/Dawson America/Dawson_Creek
America/Denver America/Detroit America/Dominica America/Edmonton
America/Eirunepe America/El_Salvador America/Fort_Nelson America/Fortaleza
America/Glace_Bay America/Goose_Bay America/Grand_Turk America/Grenada
America/Guadeloupe America/Guatemala America/Guayaquil America/Guyana
America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis
America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City
America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Inuvik
America/Iqaluit America/Jamaica America/Juneau America/Kentucky/Louisville
America/Kentucky/Monticello America/Kralendijk America/La_Paz America/Lima
America/Los_Angeles America/Lower_Princes America/Maceio America/Managua
America/Manaus America/Marigot America/Martinique America/Matamoros
America/Mazatlan America/Menominee America/Merida America/Metlakatla
America/Mexico_City America/Miquelon America/Moncton America/Monterrey
America/Montevideo America/Montserrat America/Nassau America/New_York
America/Nipigon America/Nome America/Noronha America/North_Dakota/Beulah
America/North_Dakota/Center America/North_Dakota/New_Salem America/Nuuk America/Ojinaga
America/Panama America/Pangnirtung America/Paramaribo America/Phoenix
America/Port-au-Prince America/Port_of_Spain America/Porto_Velho America/Puerto_Rico
America/Punta_Arenas America/Rainy_River America/Rankin_Inlet America/Recife
America/Regina America/Resolute America/Rio_Branco America/Santarem
America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund
America/Sitka America/St_Barthelemy America/St_Johns America/St_Kitts
America/St_Lucia America/St_Thomas America/St_Vincent America/Swift_Current
America/Tegucigalpa America/Thule America/Thunder_Bay America/Tijuana
America/Toronto America/Tortola America/Vancouver America/Whitehorse
America/Winnipeg America/Yakutat America/Yellowknife  


Antarctica

Antarctica
Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie
Antarctica/Mawson Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera
Antarctica/Syowa Antarctica/Troll Antarctica/Vostok  


Arctic

Arctic
Arctic/Longyearbyen


Asia

Asia
Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr
Asia/Aqtau Asia/Aqtobe Asia/Ashgabat Asia/Atyrau
Asia/Baghdad Asia/Bahrain Asia/Baku Asia/Bangkok
Asia/Barnaul Asia/Beirut Asia/Bishkek Asia/Brunei
Asia/Chita Asia/Choibalsan Asia/Colombo Asia/Damascus
Asia/Dhaka Asia/Dili Asia/Dubai Asia/Dushanbe
Asia/Famagusta Asia/Gaza Asia/Hebron Asia/Ho_Chi_Minh
Asia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/Jakarta
Asia/Jayapura Asia/Jerusalem Asia/Kabul Asia/Kamchatka
Asia/Karachi Asia/Kathmandu Asia/Khandyga Asia/Kolkata
Asia/Krasnoyarsk Asia/Kuala_Lumpur Asia/Kuching Asia/Kuwait
Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila
Asia/Muscat Asia/Nicosia Asia/Novokuznetsk Asia/Novosibirsk
Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak
Asia/Pyongyang Asia/Qatar Asia/Qostanay Asia/Qyzylorda
Asia/Riyadh Asia/Sakhalin Asia/Samarkand Asia/Seoul
Asia/Shanghai Asia/Singapore Asia/Srednekolymsk Asia/Taipei
Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Thimphu
Asia/Tokyo Asia/Tomsk Asia/Ulaanbaatar Asia/Urumqi
Asia/Ust-Nera Asia/Vientiane Asia/Vladivostok Asia/Yakutsk
Asia/Yangon Asia/Yekaterinburg Asia/Yerevan  


Atlantic

Atlantic
Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde
Atlantic/Faroe Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia
Atlantic/St_Helena Atlantic/Stanley    


Australia

Australia
Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Currie
Australia/Darwin Australia/Eucla Australia/Hobart Australia/Lindeman
Australia/Lord_Howe Australia/Melbourne Australia/Perth Australia/Sydney


Europe

Europe
Europe/Amsterdam Europe/Andorra Europe/Astrakhan Europe/Athens
Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels
Europe/Bucharest Europe/Budapest Europe/Busingen Europe/Chisinau
Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey
Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey
Europe/Kaliningrad Europe/Kiev Europe/Kirov Europe/Lisbon
Europe/Ljubljana Europe/London Europe/Luxembourg Europe/Madrid
Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco
Europe/Moscow Europe/Oslo Europe/Paris Europe/Podgorica
Europe/Prague Europe/Riga Europe/Rome Europe/Samara
Europe/San_Marino Europe/Sarajevo Europe/Saratov Europe/Simferopol
Europe/Skopje Europe/Sofia Europe/Stockholm Europe/Tallinn
Europe/Tirane Europe/Ulyanovsk Europe/Uzhgorod Europe/Vaduz
Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd
Europe/Warsaw Europe/Zagreb Europe/Zaporozhye Europe/Zurich


Indian

Indian
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos
Indian/Comoro Indian/Kerguelen Indian/Mahe Indian/Maldives
Indian/Mauritius Indian/Mayotte Indian/Reunion  


Pacific

Pacific
Pacific/Apia Pacific/Auckland Pacific/Bougainville Pacific/Chatham
Pacific/Chuuk Pacific/Easter Pacific/Efate Pacific/Enderbury
Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos
Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu
Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro
Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue
Pacific/Norfolk Pacific/Noumea Pacific/Pago_Pago Pacific/Palau
Pacific/Pitcairn Pacific/Pohnpei Pacific/Port_Moresby Pacific/Rarotonga
Pacific/Saipan Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu
Pacific/Wake Pacific/Wallis    


Others

Warning

Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons, and may expose erroneous behavior.

Warning

If you disregard the above warning, please also note that the IANA timezone database that provides PHP's timezone support uses POSIX style signs, which results in the Etc/GMT+n and Etc/GMT-n time zones being reversed from common usage.

For example, the time zone 8 hours ahead of GMT that is used in China and Western Australia (among other places) is actually Etc/GMT-8 in this database, not Etc/GMT+8 as you would normally expect.

Once again, it is strongly recommended that you use the correct time zone for your location, such as Asia/Shanghai or Australia/Perth for the above examples.

Others
Africa/Asmera Africa/Timbuktu America/Argentina/ComodRivadavia America/Atka
America/Buenos_Aires America/Catamarca America/Coral_Harbour America/Cordoba
America/Ensenada America/Fort_Wayne America/Godthab America/Indianapolis
America/Jujuy America/Knox_IN America/Louisville America/Mendoza
America/Montreal America/Porto_Acre America/Rosario America/Santa_Isabel
America/Shiprock America/Virgin Antarctica/South_Pole Asia/Ashkhabad
Asia/Calcutta Asia/Chongqing Asia/Chungking Asia/Dacca
Asia/Harbin Asia/Istanbul Asia/Kashgar Asia/Katmandu
Asia/Macao Asia/Rangoon Asia/Saigon Asia/Tel_Aviv
Asia/Thimbu Asia/Ujung_Pandang Asia/Ulan_Bator Atlantic/Faeroe
Atlantic/Jan_Mayen Australia/ACT Australia/Canberra Australia/LHI
Australia/North Australia/NSW Australia/Queensland Australia/South
Australia/Tasmania Australia/Victoria Australia/West Australia/Yancowinna
Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West
Canada/Atlantic Canada/Central Canada/Eastern Canada/Mountain
Canada/Newfoundland Canada/Pacific Canada/Saskatchewan Canada/Yukon
CET Chile/Continental Chile/EasterIsland CST6CDT
Cuba EET Egypt Eire
EST EST5EDT Etc/GMT Etc/GMT+0
Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12
Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5
Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9
Etc/GMT-0 Etc/GMT-1 Etc/GMT-10 Etc/GMT-11
Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2
Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6
Etc/GMT-7 Etc/GMT-8 Etc/GMT-9 Etc/GMT0
Etc/Greenwich Etc/UCT Etc/Universal Etc/UTC
Etc/Zulu Europe/Belfast Europe/Nicosia Europe/Tiraspol
Factory GB GB-Eire GMT
GMT+0 GMT-0 GMT0 Greenwich
Hongkong HST Iceland Iran
Israel Jamaica Japan Kwajalein
Libya MET Mexico/BajaNorte Mexico/BajaSur
Mexico/General MST MST7MDT Navajo
NZ NZ-CHAT Pacific/Johnston Pacific/Ponape
Pacific/Samoa Pacific/Truk Pacific/Yap Poland
Portugal PRC PST8PDT ROC
ROK Singapore Turkey UCT
Universal US/Alaska US/Aleutian US/Arizona
US/Central US/East-Indiana US/Eastern US/Hawaii
US/Indiana-Starke US/Michigan US/Mountain US/Pacific
US/Pacific-New US/Samoa UTC W-SU
WET Zulu    




High resolution timing


Introduction

The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlaying APIs.

Note: As of PHP 7.3.0 the related function hrtime() is part of the core.



Installing/Configuring

Table of Contents


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/hrtime.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.




Examples

Table of Contents


Basic usage

The example illustrates the basic StopWatch class usage

Example #1 Measure several code blocks execution and get the total

<?php

$c 
= new HRTime\StopWatch;

$c->start();
/* measure this code block execution */
for ($i 0$i 1024*1024$i++);
$c->stop();
$elapsed0 $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

/* measurement is not running here*/
for ($i 0$i 1024*1024$i++);

$c->start();
/* measure this code block execution */
for ($i 0$i 1024*1024$i++);
$c->stop();
$elapsed1 $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

$elapsed_total $c->getElapsedTime(HRTime\Unit::NANOSECOND);

?>



The HRTime\PerformanceCounter class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\PerformanceCounter {
/* Methods */
public static getFrequency ( void ) : int
public static getTicks ( void ) : int
public static getTicksSince ( int $start ) : int
}

HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequencyTimer frequency in ticks per second

Description

public static HRTime\PerformanceCounter::getFrequency ( void ) : int

Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.

Parameters

This function has no parameters.

Return Values

Returns integer indicating the timer frequency.



HRTime\PerformanceCounter::getTicks

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicksCurrent ticks from the system

Description

public static HRTime\PerformanceCounter::getTicks ( void ) : int

Returns the ticks count.

Parameters

This function has no parameters.

Return Values

Returns integer indicating the ticks count.



HRTime\PerformanceCounter::getTicksSince

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicksSinceTicks elapsed since the given value

Description

public static HRTime\PerformanceCounter::getTicksSince ( int $start ) : int

Returns the ticks count elapsed since the given start value.

Parameters

start

Starting ticks value.

Return Values

Returns integer indicating the ticks count.


Table of Contents



The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\StopWatch extends HRTime\PerformanceCounter {
/* Methods */
public getElapsedTicks ( void ) : int
public getElapsedTime ([ int $unit ] ) : float
public getLastElapsedTicks ( void ) : int
public getLastElapsedTime ([ int $unit ] ) : float
public isRunning ( void ) : bool
public start ( void ) : void
public stop ( void ) : void
/* Inherited methods */
public static HRTime\PerformanceCounter::getFrequency ( void ) : int
public static HRTime\PerformanceCounter::getTicks ( void ) : int
public static HRTime\PerformanceCounter::getTicksSince ( int $start ) : int
}

HRTime\StopWatch::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTicksGet elapsed ticks for all intervals

Description

public HRTime\StopWatch::getElapsedTicks ( void ) : int

Get elapsed ticks for all the previously closed intervals.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.



HRTime\StopWatch::getElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTimeGet elapsed time for all intervals

Description

public HRTime\StopWatch::getElapsedTime ([ int $unit ] ) : float

Get elapsed time for all the previously closed intervals.

Parameters

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Return Values

Returns float indicating elapsed time.



HRTime\StopWatch::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTicksGet elapsed ticks for the last interval

Description

public HRTime\StopWatch::getLastElapsedTicks ( void ) : int

Get elapsed ticks for the previously closed interval.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.



HRTime\StopWatch::getLastElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTimeGet elapsed time for the last interval

Description

public HRTime\StopWatch::getLastElapsedTime ([ int $unit ] ) : float

Get elapsed time for the previously closed interval.

Parameters

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

Return Values

Returns float indicating elapsed time.



HRTime\StopWatch::isRunning

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::isRunningWhether the measurement is running

Description

public HRTime\StopWatch::isRunning ( void ) : bool

Reveals whether the measurement was started.

Parameters

This function has no parameters.

Return Values

Returns boolean indicating whetehr the measurement is running.



HRTime\StopWatch::start

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::startStart time measurement

Description

public HRTime\StopWatch::start ( void ) : void

Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.

Parameters

This function has no parameters.

Return Values

Returns void.



HRTime\StopWatch::stop

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::stopStop time measurement

Description

public HRTime\StopWatch::stop ( void ) : void

Stop the time measurement for the previously started interval.

Parameters

This function has no parameters.

Return Values

Returns void.


Table of Contents



The HRTime\Unit class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\Unit {
/* Constants */
const integer SECOND = 0 ;
const integer MILLISECOND = 1 ;
const integer MICROSECOND = 2 ;
const integer NANOSECOND = 3 ;
/* Methods */
}

Predefined Constants

HRTime\Unit::SECOND

HRTime\Unit::MILLISECOND

HRTime\Unit::MICROSECOND

HRTime\Unit::NANOSECOND





File System Related Extensions


Direct IO


Introduction

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/dio.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

One resource type is defined by this extension: a file descriptor returned by dio_open().




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

F_DUPFD (integer)

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)



Direct IO Functions


dio_close

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_closeCloses the file descriptor given by fd

Description

dio_close ( resource $fd ) : void

The function dio_close() closes the file descriptor fd.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

No value is returned.

Examples

Example #1 Closing an open file descriptor

<?php
$fd 
dio_open('/dev/ttyS0'O_RDWR);

dio_close($fd);
?>

See Also

  • dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow



dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_fcntlPerforms a c library fcntl on fd

Description

dio_fcntl ( resource $fd , int $cmd [, mixed $args ] ) : mixed

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

Parameters

fd

The file descriptor returned by dio_open().

cmd

Can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described below) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater than or equal to args and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by args, which can be O_APPEND, O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

args

args is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • start - offset where lock begins

  • length - size of locked area. zero means to end of file

  • whence - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • type - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Return Values

Returns the result of the C call.

Examples

Example #1 Setting and clearing a lock

<?php

$fd 
dio_open('/dev/ttyS0'O_RDWR);

if (
dio_fcntl($fdF_SETLK, Array("type"=>F_WRLCK)) == -1) {
   
// the file descriptor appears locked
   
echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo 
"Lock successfully set/cleared";
}

dio_close($fd);
?>

Notes

Note: This function is not implemented on Windows platforms.



dio_open

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_open Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow

Description

dio_open ( string $filename , int $flags [, int $mode = 0 ] ) : resource

dio_open() opens a file and returns a new file descriptor for it.

Parameters

filename

The pathname of the file to open.

flags

The flags parameter is a bitwise-ORed value comprising flags from the following list. This value must include one of O_RDONLY, O_WRONLY, or O_RDWR. Additionally, it may include any combination of the other flags from this list.

  • O_RDONLY - opens the file for read access.

  • O_WRONLY - opens the file for write access.

  • O_RDWR - opens the file for both reading and writing.

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both O_CREAT and O_EXCL are set and the file already exists, dio_open() will fail.

  • O_TRUNC - if the file exists and is opened for write access, the file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of the file.

  • O_NONBLOCK - sets non blocking mode.

  • O_NOCTTY - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file.

mode

If flags contains O_CREAT, mode will set the permissions of the file (creation permissions). mode is required for correct operation when O_CREAT is specified in flags and is ignored otherwise.

The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

Return Values

A file descriptor or FALSE on error.

Examples

Example #1 Opening a file descriptor

<?php

$fd 
dio_open('/dev/ttyS0'O_RDWR O_NOCTTY O_NONBLOCK);

dio_close($fd);
?>

See Also



dio_read

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_readReads bytes from a file descriptor

Description

dio_read ( resource $fd [, int $len = 1024 ] ) : string

The function dio_read() reads and returns len bytes from file with descriptor fd.

Parameters

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

Return Values

The bytes read from fd.

See Also

  • dio_write() - Writes data to fd with optional truncation at length



dio_seek

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_seekSeeks to pos on fd from whence

Description

dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] ) : int

The function dio_seek() is used to change the file position of the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

Return Values

Examples

Example #1 Positioning in a file

<?php

$fd 
dio_open('/dev/ttyS0'O_RDWR);

dio_seek($fd10SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd10SEEK_END);
// position is now at 10 characters past the end of the file. 
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>



dio_stat

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_stat Gets stat information about the file descriptor fd

Description

dio_stat ( resource $fd ) : array

dio_stat() returns information about the given file descriptor.

Parameters

fd

The file descriptor returned by dio_open().

Return Values

Returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.



dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 < 5.1.0)

dio_tcsetattr Sets terminal attributes and baud rate for a serial port

Description

dio_tcsetattr ( resource $fd , array $options ) : bool

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

Parameters

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

Return Values

No value is returned.

Examples

Example #1 Setting the baud rate on a serial port

<?php

$fd 
dio_open('/dev/ttyS0'O_RDWR O_NOCTTY O_NONBLOCK);

dio_fcntl($fdF_SETFLO_SYNC);

dio_tcsetattr($fd, array(
  
'baud' => 9600,
  
'bits' => 8,
  
'stop'  => 1,
  
'parity' => 0
)); 

while (
1) {

  
$data dio_read($fd256);

  if (
$data) {
      echo 
$data;
  }


?>

Notes

Note: This function is not implemented on Windows platforms.



dio_truncate

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_truncate Truncates file descriptor fd to offset bytes

Description

dio_truncate ( resource $fd , int $offset ) : bool

dio_truncate() truncates a file to at most offset bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

Parameters

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not implemented on Windows platforms.



dio_write

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_write Writes data to fd with optional truncation at length

Description

dio_write ( resource $fd , string $data [, int $len = 0 ] ) : int

dio_write() writes up to len bytes from data to file fd.

Parameters

fd

The file descriptor returned by dio_open().

data

The written data.

len

The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

Return Values

Returns the number of bytes written to fd.

See Also


Table of Contents

  • dio_close — Closes the file descriptor given by fd
  • dio_fcntl — Performs a c library fcntl on fd
  • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow
  • dio_read — Reads bytes from a file descriptor
  • dio_seek — Seeks to pos on fd from whence
  • dio_stat — Gets stat information about the file descriptor fd
  • dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
  • dio_truncate — Truncates file descriptor fd to offset bytes
  • dio_write — Writes data to fd with optional truncation at length



Directories


Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

There is no installation needed to use these functions; they are part of the PHP core.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Semicolon on Windows, colon otherwise.
SCANDIR_SORT_ASCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_DESCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_NONE (integer)
Available since PHP 5.4.0.


The Directory class

(PHP 4, PHP 5, PHP 7)

Introduction

Instances of Directory are created by calling the dir() function, not by the new operator.

Class synopsis

Directory {
/* Properties */
public string path ;
public resource handle ;
/* Methods */
public close ([ resource $dir_handle ] ) : void
public read ([ resource $dir_handle ] ) : string
public rewind ([ resource $dir_handle ] ) : void
}

Properties

path

The directory that was opened.

handle

Can be used with other directory functions such as readdir(), rewinddir() and closedir().


Directory::close

(PHP 4, PHP 5, PHP 7)

Directory::closeClose directory handle

Description

public Directory::close ([ resource $dir_handle ] ) : void

Same as closedir(), only dir_handle defaults to $this->handle.



Directory::read

(PHP 4, PHP 5, PHP 7)

Directory::readRead entry from directory handle

Description

public Directory::read ([ resource $dir_handle ] ) : string

Same as readdir(), only dir_handle defaults to $this->handle.



Directory::rewind

(PHP 4, PHP 5, PHP 7)

Directory::rewindRewind directory handle

Description

public Directory::rewind ([ resource $dir_handle ] ) : void

Same as rewinddir(), only dir_handle defaults to $this->handle.


Table of Contents



Directory Functions

See Also

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.


chdir

(PHP 4, PHP 5, PHP 7)

chdirChange directory

Description

chdir ( string $directory ) : bool

Changes PHP's current directory to directory.

Parameters

directory

The new current directory

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an error of level E_WARNING on failure.

Examples

Example #1 chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

   /home/vincent
   /home/vincent/public_html
   

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

Caution

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, any changes to the current directory made through chdir() will be invisible to the operating system. All built-in PHP functions will still respect the change in current directory; but external library functions called using FFI will not. You can tell whether your copy of PHP was built with ZTS enabled using php -i or the built-in constant PHP_ZTS.

See Also

  • getcwd() - Gets the current working directory



chroot

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

chrootChange the root directory

Description

chroot ( string $directory ) : bool

Changes the root directory of the current process to directory, and changes the current working directory to "/".

This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.

Parameters

directory

The path to change the root directory to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 chroot() example

<?php
chroot
("/path/to/your/chroot/");
echo 
getcwd();
?>

The above example will output:

   /
   

Notes

Note: This function is not implemented on Windows platforms.

Note: This function is not available in PHP interpreters built with ZTS (Zend Thread Safety) enabled. To check whether your copy of PHP was built with ZTS enabled, use php -i or test the built-in constant PHP_ZTS.



closedir

(PHP 4, PHP 5, PHP 7)

closedirClose directory handle

Description

closedir ([ resource $dir_handle ] ) : void

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Examples

Example #1 closedir() example

<?php
$dir 
"/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if (
$dh opendir($dir)) {
        
$directory readdir($dh);
        
closedir($dh);
    }
}
?>



dir

(PHP 4, PHP 5, PHP 7)

dirReturn an instance of the Directory class

Description

dir ( string $directory [, resource $context ] ) : Directory

A pseudo-object oriented mechanism for reading a directory. The given directory is opened.

Parameters

directory

Directory to open

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

Examples

Example #1 dir() example

Please note the fashion in which Directory::read()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as - see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

<?php
$d 
dir("/etc/php5");
echo 
"Handle: " $d->handle "\n";
echo 
"Path: " $d->path "\n";
while (
false !== ($entry $d->read())) {
   echo 
$entry."\n";
}
$d->close();
?>

The above example will output something similar to:

   Handle: Resource id #2
   Path: /etc/php5
   .
   ..
   apache
   cgi
   cli
   

Notes

Note:

The order in which directory entries are returned by the read method is system-dependent.



getcwd

(PHP 4, PHP 5, PHP 7)

getcwdGets the current working directory

Description

getcwd ( void ) : string

Gets the current working directory.

Return Values

Returns the current working directory on success, or FALSE on failure.

On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.

Caution

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, the current working directory returned by getcwd() may be different from that returned by operating system interfaces. External libraries (invoked through FFI) which depend on the current working directory will be affected.

Examples

Example #1 getcwd() example

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

   /home/didou
   /home/didou/cvs
   

See Also



opendir

(PHP 4, PHP 5, PHP 7)

opendirOpen directory handle

Description

opendir ( string $path [, resource $context ] ) : resource

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parameters

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns a directory handle resource on success, or FALSE on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

This may happen if path is not a valid directory, the directory can not be opened due to permission restrictions, or due to filesystem errors.

Examples

Example #1 opendir() example

<?php
$dir 
"/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if (
$dh opendir($dir)) {
        while ((
$file readdir($dh)) !== false) {
            echo 
"filename: $file : filetype: " filetype($dir $file) . "\n";
        }
        
closedir($dh);
    }
}
?>

The above example will output something similar to:

   filename: . : filetype: dir
   filename: .. : filetype: dir
   filename: apache : filetype: dir
   filename: cgi : filetype: dir
   filename: cli : filetype: dir
   

See Also

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • dir() - Return an instance of the Directory class



readdir

(PHP 4, PHP 5, PHP 7)

readdirRead entry from directory handle

Description

readdir ([ resource $dir_handle ] ) : string

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Return Values

Returns the entry name on success or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 List all entries in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php

if ($handle opendir('/path/to/files')) {
    echo 
"Directory handle: $handle\n";
    echo 
"Entries:\n";

    
/* This is the correct way to loop over the directory. */
    
while (false !== ($entry readdir($handle))) {
        echo 
"$entry\n";
    }

    
/* This is the WRONG way to loop over the directory. */
    
while ($entry readdir($handle)) {
        echo 
"$entry\n";
    }

    
closedir($handle);
}
?>

Example #2 List all entries in the current directory and strip out . and ..

<?php
if ($handle opendir('.')) {
    while (
false !== ($entry readdir($handle))) {
        if (
$entry != "." && $entry != "..") {
            echo 
"$entry\n";
        }
    }
    
closedir($handle);
}
?>

See Also

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path



rewinddir

(PHP 4, PHP 5, PHP 7)

rewinddirRewind directory handle

Description

rewinddir ([ resource $dir_handle ] ) : void

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Return Values

Returns NULL on success or FALSE on failure.



scandir

(PHP 5, PHP 7)

scandirList files and directories inside the specified path

Description

scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] ) : array

Returns an array of files and directories from the directory.

Parameters

directory

The directory that will be scanned.

sorting_order

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

Changelog

Version Description
5.4.0 sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.

Examples

Example #1 A simple scandir() example

<?php
$dir    
'/tmp';
$files1 scandir($dir);
$files2 scandir($dir1);

print_r($files1);
print_r($files2);
?>

The above example will output something similar to:

   Array
   (
       [0] => .
       [1] => ..
       [2] => bar.php
       [3] => foo.txt
       [4] => somedir
   )
   Array
   (
       [0] => somedir
       [1] => foo.txt
       [2] => bar.php
       [3] => ..
       [4] => .
   )
   

Notes

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • glob() - Find pathnames matching a pattern
  • is_dir() - Tells whether the filename is a directory
  • sort() - Sort an array


Table of Contents

  • chdir — Change directory
  • chroot — Change the root directory
  • closedir — Close directory handle
  • dir — Return an instance of the Directory class
  • getcwd — Gets the current working directory
  • opendir — Open directory handle
  • readdir — Read entry from directory handle
  • rewinddir — Rewind directory handle
  • scandir — List files and directories inside the specified path



File Information


Introduction

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.



Installing/Configuring

Table of Contents


Requirements

Before PHP 5.3.0, the magic_open library is needed to build this extension.



Installation

This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there. However, versions prior to 5.3+ may use the » discontinued PECL extension.

Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.

The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.

Upgrade history of the bundled libmagic library
PHP Version Updated libmagic Version Notes
5.3.2 5.03  
5.3.0 5.02  



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FILEINFO_NONE (integer)
No special handling.
Follow symlinks.
FILEINFO_MIME_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to thread safety issues.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal representation.
FILEINFO_EXTENSION (integer)
Returns the file extension appropriate for the MIME type detected in the file. For types that commonly have multiple file extensions, such as JPEG images, then the return value is multiple extensions separated by a forward slash e.g.: "jpeg/jpg/jpe/jfif". For unknown types not available in the magic.mime database, then return value is "???". Available since PHP 7.2.0.


Fileinfo Functions


finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::bufferReturn information about a string buffer

Description

Procedural style

finfo_buffer ( resource $finfo , string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

Object oriented style

public finfo::buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is used to get information about binary data in a string.

Parameters

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_buffer() example

<?php
$finfo 
= new finfo(FILEINFO_MIME);
echo 
$finfo->buffer($_POST["script"]) . "\n";
?>

The above example will output something similar to:

   application/x-sh; charset=us-ascii
   

See Also



finfo_close

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_closeClose fileinfo resource

Description

finfo_close ( resource $finfo ) : bool

This function closes the resource opened by finfo_open().

Parameters

finfo

Fileinfo resource returned by finfo_open().

Return Values

Returns TRUE on success or FALSE on failure.



finfo_file

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::fileReturn information about a file

Description

Procedural style

finfo_file ( resource $finfo , string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

Object oriented style

public finfo::file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is used to get information about a file.

Parameters

finfo

Fileinfo resource returned by finfo_open().

file_name

Name of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

For a description of contexts, refer to Stream Functions.

Return Values

Returns a textual description of the contents of the file_name argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_file() example

<?php
$finfo 
finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo 
finfo_file($finfo$filename) . "\n";
}
finfo_close($finfo);
?>

The above example will output something similar to:

   text/html
   image/gif
   application/vnd.ms-excel
   

See Also



finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__constructCreate a new fileinfo resource

Description

Procedural style

finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] ) : resource

Object oriented style (constructor):

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )

This function opens a magic database and returns its resource.

Parameters

options

One or disjunction of more Fileinfo constants.

magic_file

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If the environment variable isn't set, then PHP's bundled magic database will be used.

Passing NULL or an empty string will be equivalent to the default value.

Return Values

(Procedural style only) Returns a magic database resource on success or FALSE on failure.

Notes

Warning

The expected magic database format changed in PHP 5.3.11 and 5.4.1. Due to this, the internal magic database was upgraded. This mostly effects code where an external magic database is used: reading an older magic file will now fail. Also, some textual representations of the mime types has changed, for instance for PHP would be "PHP script, ASCII text" instead of "PHP script text" returned.

Note:

Generally, using the bundled magic database (by leaving magic_file and the MAGIC environment variables unset) is the best course of action unless you specifically need a custom magic database.

Examples

Example #1 Object oriented style

<?php
$finfo 
= new finfo(FILEINFO_MIME"/usr/share/misc/magic"); // return mime type ala mimetype extension

/* get mime-type for a specific file */
$filename "/usr/local/something.txt";
echo 
$finfo->file($filename);

?>

Example #2 Procedural style

<?php
$finfo 
finfo_open(FILEINFO_MIME"/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo 
"Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename "/usr/local/something.txt";
echo 
finfo_file($finfo$filename);

/* close connection */
finfo_close($finfo);
?>

The above example will output:

   text/plain; charset=us-ascii
   

See Also



finfo_set_flags

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flagsSet libmagic configuration options

Description

Procedural style

finfo_set_flags ( resource $finfo , int $options ) : bool

Object oriented style

public finfo::set_flags ( int $options ) : bool

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

Parameters

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Return Values

Returns TRUE on success or FALSE on failure.



mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mime_content_typeDetect MIME Content-type for a file

Description

mime_content_type ( string $filename ) : string

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parameters

filename

Path to the tested file.

Return Values

Returns the content type in MIME format, like text/plain or application/octet-stream, or FALSE on failure.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 mime_content_type() Example

<?php
echo mime_content_type('php.gif') . "\n";
echo 
mime_content_type('test.php');
?>

The above example will output:

   image/gif
   text/plain
   

See Also


Table of Contents



The finfo class

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

Introduction

This class provides an object oriented interface into the fileinfo functions.

Class synopsis

finfo {
public __construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )
public buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
public file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
public set_flags ( int $options ) : bool
}

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo::bufferAlias of finfo_buffer()

Description

public finfo::buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is an alias of: finfo_buffer()



finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::__constructAlias of finfo_open()

Description

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )

This function is an alias of: finfo_open()



finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::fileAlias of finfo_file()

Description

public finfo::file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is an alias of: finfo_file()



finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::set_flagsAlias of finfo_set_flags()

Description

public finfo::set_flags ( int $options ) : bool

This function is an alias of: finfo_set_flags()


Table of Contents




Filesystem


Introduction

No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

There is no installation needed to use these functions; they are part of the PHP core.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filesystem and Streams Configuration Options
Name Default Changeable Changelog
allow_url_fopen "1" PHP_INI_SYSTEM  
allow_url_include "0" PHP_INI_SYSTEM Available since PHP 5.2.0. Deprecated as of PHP 7.4.0.
user_agent NULL PHP_INI_ALL  
default_socket_timeout "60" PHP_INI_ALL  
from "" PHP_INI_ALL  
auto_detect_line_endings "0" PHP_INI_ALL  
sys_temp_dir "" PHP_INI_SYSTEM Available since PHP 5.5.0.

Here's a short explanation of the configuration directives.

allow_url_fopen boolean

This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

allow_url_include boolean

This option allows the use of URL-aware fopen wrappers with the following functions: include, include_once, require, require_once.

Note:

This setting requires allow_url_fopen to be on.

user_agent string

Define the user agent for PHP to send.

default_socket_timeout integer

Default timeout (in seconds) for socket based streams. Specifying a negative value means an infinite timeout.

from string

The email address to be used on unauthenticated FTP connections and as the value of From header for HTTP connections, when using the ftp and http wrappers, respectively.

auto_detect_line_endings boolean

When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

sys_temp_dir string



Resource Types

The file system uses streams as their resource type. Streams are documented in its own reference chapter, Streams.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SEEK_SET (integer)
SEEK_CUR (integer)
SEEK_END (integer)
LOCK_SH (integer)
LOCK_EX (integer)
LOCK_UN (integer)
LOCK_NB (integer)
GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path.
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters.
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines.
FILE_BINARY (integer)

Binary mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

FILE_TEXT (integer)

Text mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
INI_SCANNER_TYPED (integer)
Typed INI scanner mode (since PHP 5.6.1).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.


Filesystem Functions

See Also

For related functions, see also the Directory and Program Execution sections.

For a list and explanation of the various URL wrappers that can be used as remote files, see also Supported Protocols and Wrappers.


basename

(PHP 4, PHP 5, PHP 7)

basenameReturns trailing name component of path

Description

basename ( string $path [, string $suffix ] ) : string

Given a string containing the path to a file or directory, this function will return the trailing name component.

Note:

basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Caution

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

suffix

If the name component ends in suffix this will also be cut off.

Return Values

Returns the base name of the given path.

Examples

Example #1 basename() example

<?php
echo "1) ".basename("/etc/sudoers.d"".d").PHP_EOL;
echo 
"2) ".basename("/etc/sudoers.d").PHP_EOL;
echo 
"3) ".basename("/etc/passwd").PHP_EOL;
echo 
"4) ".basename("/etc/").PHP_EOL;
echo 
"5) ".basename(".").PHP_EOL;
echo 
"6) ".basename("/");
?>

The above example will output:

   1) sudoers
   2) sudoers.d
   3) passwd
   4) etc
   5) .
   6) 
   

See Also

  • dirname() - Returns a parent directory's path
  • pathinfo() - Returns information about a file path



chgrp

(PHP 4, PHP 5, PHP 7)

chgrpChanges file group

Description

chgrp ( string $filename , mixed $group ) : bool

Attempts to change the group of the file filename to group.

Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Parameters

filename

Path to the file.

group

A group name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing a file's group

<?php
$filename 
'shared_file.txt';
$format "%s's Group ID @ %s: %d\n";
printf($format$filenamedate('r'), filegroup($filename));
chgrp($filename8);
clearstatcache(); // do not cache filegroup() results
printf($format$filenamedate('r'), filegroup($filename));
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: On Windows, this function fails silently when applied on a regular file.

See Also



chmod

(PHP 4, PHP 5, PHP 7)

chmodChanges file mode

Description

chmod ( string $filename , int $mode ) : bool

Attempts to change the mode of the specified file to that given in mode.

Parameters

filename

Path to the file.

mode

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly.

<?php
chmod
("/somedir/somefile"755);   // decimal; probably incorrect
chmod("/somedir/somefile""u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile"0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile"0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile"0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile"0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile"0750);
?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note:

When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

See Also



chown

(PHP 4, PHP 5, PHP 7)

chownChanges file owner

Description

chown ( string $filename , mixed $user ) : bool

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parameters

filename

Path to the file.

user

A user name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple chown() usage

<?php

// File name and username to use
$file_name"foo.php";
$path "/home/sites/php.net/public_html/sandbox/" $file_name ;
$user_name "root";

// Set the user
chown($path$user_name);

// Check the result
$stat stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

The above example will output something similar to:

   Array
   (
       [name] => root
       [passwd] => x
       [uid] => 0
       [gid] => 0
       [gecos] => root
       [dir] => /root
       [shell] => /bin/bash
   )
   

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: On Windows, this function fails silently when applied on a regular file.

See Also



clearstatcache

(PHP 4, PHP 5, PHP 7)

clearstatcacheClears file status cache

Description

clearstatcache ([ bool $clear_realpath_cache = FALSE [, string $filename ]] ) : void

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file. However unlink() clears the cache automatically.

Note:

This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

Parameters

clear_realpath_cache

Whether to clear the realpath cache or not.

filename

Clear the realpath and the stat cache for a specific filename only; only used if clear_realpath_cache is TRUE.

Return Values

No value is returned.

Changelog

Version Description
5.3.0 Added optional clear_realpath_cache and filename parameters.

Examples

Example #1 clearstatcache() example

<?php
$file 
'output_log.txt';

function 
get_owner($file)
{
    
$stat stat($file);
    
$user posix_getpwuid($stat['uid']);
    return 
$user['name'];
}

$format "UID @ %s: %s\n";

printf($formatdate('r'), get_owner($file));

chown($file'ross');
printf($formatdate('r'), get_owner($file));

clearstatcache();
printf($formatdate('r'), get_owner($file));
?>

The above example will output something similar to:

   UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
   UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
   UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
   



copy

(PHP 4, PHP 5, PHP 7)

copyCopies file

Description

copy ( string $source , string $dest [, resource $context ] ) : bool

Makes a copy of the file source to dest.

If you wish to move a file, use the rename() function.

Parameters

source

Path to the source file.

dest

The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Warning

If the destination file already exists, it will be overwritten.

context

A valid context resource created with stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.3.4 Changed the context parameter to actually have an effect. Previously, any context was ignored.
5.3.0 Added context support.

Examples

Example #1 copy() example

<?php
$file 
'example.txt';
$newfile 'example.txt.bak';

if (!
copy($file$newfile)) {
    echo 
"failed to copy $file...\n";
}
?>

See Also



delete

deleteSee unlink() or unset()

Description

There is no delete keyword or function in the PHP language. If you arrived at this page seeking to delete a file, try unlink(). To delete a variable from the local scope, check out unset().

See Also



dirname

(PHP 4, PHP 5, PHP 7)

dirnameReturns a parent directory's path

Description

dirname ( string $path [, int $levels = 1 ] ) : string

Given a string containing the path of a file or directory, this function will return the parent directory's path that is levels up from the current directory.

Note:

dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Caution

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

Parameters

path

A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

levels

The number of parent directories to go up.

This must be an integer greater than 0.

Return Values

Returns the path of a parent directory. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.

Changelog

Version Description
7.0.0 Added the optional levels parameter.

Examples

Example #1 dirname() example

<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo 
dirname("/etc/") . PHP_EOL;
echo 
dirname(".") . PHP_EOL;
echo 
dirname("C:\\") . PHP_EOL;
echo 
dirname("/usr/local/lib"2);

The above example will output something similar to:

   /etc
   / (or \ on Windows)
   .
   C:\
   /usr
   

See Also

  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname



disk_free_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_free_spaceReturns available space on filesystem or disk partition

Description

disk_free_space ( string $directory ) : float

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Note:

Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.

Return Values

Returns the number of available bytes as a float or FALSE on failure.

Examples

Example #1 disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df disk_free_space("/");

// On Windows:
$df_c disk_free_space("C:");
$df_d disk_free_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also



disk_total_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_total_spaceReturns the total size of a filesystem or disk partition

Description

disk_total_space ( string $directory ) : float

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

Parameters

directory

A directory of the filesystem or disk partition.

Return Values

Returns the total number of bytes as a float or FALSE on failure.

Examples

Example #1 disk_total_space() example

<?php
// $ds contains the total number of bytes available on "/"
$ds disk_total_space("/");

// On Windows:
$ds disk_total_space("C:");
$ds disk_total_space("D:");
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

See Also



diskfreespace

(PHP 4, PHP 5, PHP 7)

diskfreespaceAlias of disk_free_space()

Description

This function is an alias of: disk_free_space().



fclose

(PHP 4, PHP 5, PHP 7)

fcloseCloses an open file pointer

Description

fclose ( resource $handle ) : bool

The file pointed to by handle is closed.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A simple fclose() example

<?php

$handle 
fopen('somefile.txt''r');

fclose($handle);

?>

See Also

  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection



feof

(PHP 4, PHP 5, PHP 7)

feofTests for end-of-file on a file pointer

Description

feof ( resource $handle ) : bool

Tests for end-of-file on a file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Notes

Warning

If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:

Example #1 Handling timeouts with feof()

<?php
function safe_feof($fp, &$start NULL) {
 
$start microtime(true);

 return 
feof($fp);
}

/* Assuming $fp is previously opened by fsockopen() */

$start NULL;
$timeout ini_get('default_socket_timeout');

while(!
safe_feof($fp$start) && (microtime(true) - $start) < $timeout)
{
 
/* Handle */
}
?>

Warning

If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.

Example #2 feof() example with an invalid file pointer

<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file""r");

// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}

fclose($file);
?>



fflush

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fflushFlushes the output to a file

Description

fflush ( resource $handle ) : bool

This function forces a write of all buffered output to the resource pointed to by the file handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 File write example using fflush()

<?php
$filename 
'bar.txt';

$file fopen($filename'r+');
rewind($file);
fwrite($file'Foo');
fflush($file);
ftruncate($fileftell($file));
fclose($file);
?>

See Also



fgetc

(PHP 4, PHP 5, PHP 7)

fgetcGets character from file pointer

Description

fgetc ( resource $handle ) : string

Gets a character from the given file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 A fgetc() example

<?php
$fp 
fopen('somefile.txt''r');
if (!
$fp) {
    echo 
'Could not open file somefile.txt';
}
while (
false !== ($char fgetc($fp))) {
    echo 
"$char\n";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • fread() - Binary-safe file read
  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fsockopen() - Open Internet or Unix domain socket connection
  • fgets() - Gets line from file pointer



fgetcsv

(PHP 4, PHP 5, PHP 7)

fgetcsvGets line from file pointer and parse for CSV fields

Description

fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] ) : array

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.

Note:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

Parameters

handle

A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

length

Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure.

Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure character (one character only).

escape

The optional escape parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Return Values

Returns an indexed array containing the fields read.

Note:

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Changelog

Version Description
7.4.0 The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.3.0 The escape parameter was added
5.1.0 The length is now optional. Default is 0, meaning no length limit.

Examples

Example #1 Read and print the entire contents of a CSV file

<?php
$row 
1;
if ((
$handle fopen("test.csv""r")) !== FALSE) {
    while ((
$data fgetcsv($handle1000",")) !== FALSE) {
        
$num count($data);
        echo 
"<p> $num fields in line $row: <br /></p>\n";
        
$row++;
        for (
$c=0$c $num$c++) {
            echo 
$data[$c] . "<br />\n";
        }
    }
    
fclose($handle);
}
?>

See Also

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by a string
  • file() - Reads entire file into an array
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer



fgets

(PHP 4, PHP 5, PHP 7)

fgetsGets line from file pointer

Description

fgets ( resource $handle [, int $length ] ) : string

Gets a line from file pointer.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.

If an error occurs, FALSE is returned.

Examples

Example #1 Reading a file line by line

<?php
$handle 
= @fopen("/tmp/inputfile.txt""r");
if (
$handle) {
    while ((
$buffer fgets($handle4096)) !== false) {
        echo 
$buffer;
    }
    if (!
feof($handle)) {
        echo 
"Error: unexpected fgets() fail\n";
    }
    
fclose($handle);
}
?>

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Note:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

See Also



fgetss

(PHP 4, PHP 5, PHP 7)

fgetssGets line from file pointer and strip HTML tags

Warning

This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.

Description

fgetss ( resource $handle [, int $length [, string $allowable_tags ]] ) : string

Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags() on the return value of fgets().

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

length

Length of the data to be retrieved.

allowable_tags

You can use the optional third parameter to specify tags which should not be stripped. See strip_tags() for details regarding allowable_tags.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle, with all HTML and PHP code stripped.

If an error occurs, returns FALSE.

Examples

Example #1 Reading a PHP file line-by-line

<?php
$str 
= <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php'$str);

$handle = @fopen("sample.php""r");
if (
$handle) {
    while (!
feof($handle)) {
        
$buffer fgetss($handle4096);
        echo 
$buffer;
    }
    
fclose($handle);
}
?>

The above example will output something similar to:

    Welcome! Today is the  of .
   
   Text outside of the HTML block.
   

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also



file_exists

(PHP 4, PHP 5, PHP 7)

file_existsChecks whether a file or directory exists

Description

file_exists ( string $filename ) : bool

Checks whether a file or directory exists.

Parameters

filename

Path to the file or directory.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Return Values

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Note:

This function will return FALSE for symlinks pointing to non-existing files.

Warning

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Note:

The check is done using the real UID/GID instead of the effective one.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 Testing whether a file exists

<?php
$filename 
'/path/to/foo.txt';

if (
file_exists($filename)) {
    echo 
"The file $filename exists";
} else {
    echo 
"The file $filename does not exist";
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Tells whether the filename is a regular file
  • file() - Reads entire file into an array



file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

file_get_contentsReads entire file into a string

Description

file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note:

If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

Parameters

filename

Name of the file to read.

use_include_path

Note:

The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int. Use TRUE instead.

context

A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.

offset

The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.

Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

maxlen

Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

Return Values

The function returns the read data or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.

Examples

Example #1 Get and output the source of the homepage of a website

<?php
$homepage 
file_get_contents('http://www.example.com/');
echo 
$homepage;
?>

Example #2 Searching within the include_path

<?php
// If strict types are enabled i.e. declare(strict_types=1);
$file file_get_contents('./people.txt'true);
// Otherwise
$file file_get_contents('./people.txt'FILE_USE_INCLUDE_PATH);
?>

Example #3 Reading a section of a file

<?php
// Read 14 characters starting from the 21st character
$section file_get_contents('./people.txt'FALSENULL2014);
var_dump($section);
?>

The above example will output something similar to:

   string(14) "lle Bjori Ro" 
   

Example #4 Using stream contexts

<?php
// Create a stream
$opts = array(
  
'http'=>array(
    
'method'=>"GET",
    
'header'=>"Accept-language: en\r\n" .
              
"Cookie: foo=bar\r\n"
  
)
);

$context stream_context_create($opts);

// Open the file using the HTTP headers set above
$file file_get_contents('http://www.example.com/'false$context);
?>

Changelog

Version Description
7.1.0 Support for negative offsets has been added.
5.1.0 Added the offset and maxlen parameters.

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also



file_put_contents

(PHP 5, PHP 7)

file_put_contentsWrite data to a file

Description

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Parameters

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Available flags
Flag Description
FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information.
FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it.
LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".

context

A valid context resource created with stream_context_create().

Return Values

This function returns the number of bytes that were written to the file, or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Simple usage example

<?php
$file 
'people.txt';
// Open the file to get existing content
$current file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file$current);
?>

Example #2 Using flags

<?php
$file 
'people.txt';
// The new person to add to the file
$person "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file$personFILE_APPEND LOCK_EX);
?>

Changelog

Version Description
5.1.0 Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

See Also



file

(PHP 4, PHP 5, PHP 7)

fileReads entire file into an array

Description

file ( string $filename [, int $flags = 0 [, resource $context ]] ) : array

Reads an entire file into an array.

Note:

You can use file_get_contents() to return the contents of a file as a string.

Parameters

filename

Path to the file.

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

flags

The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Omit newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines

context

A context resource created with the stream_context_create() function.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Note:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Errors/Exceptions

Emits an E_WARNING level error if the file does not exist.

Examples

Example #1 file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo 
"Line #<b>{$line_num}</b> : " htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html implode(''file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5
$trimmed file('somefile.txt'FILE_IGNORE_NEW_LINES FILE_SKIP_EMPTY_LINES);
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also



fileatime

(PHP 4, PHP 5, PHP 7)

fileatimeGets last access time of file

Description

fileatime ( string $filename ) : int

Gets the last access time of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last accessed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 fileatime() example

<?php

// outputs e.g.  somefile.txt was last accessed: December 29 2002 22:16:23.

$filename 'somefile.txt';
if (
file_exists($filename)) {
    echo 
"$filename was last accessed: " date("F d Y H:i:s."fileatime($filename));
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories.

Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

Note:

Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



filectime

(PHP 4, PHP 5, PHP 7)

filectimeGets inode change time of file

Description

filectime ( string $filename ) : int

Gets the inode change time of a file.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last changed, or FALSE on failure. The time is returned as a Unix timestamp.

Examples

Example #1 A filectime() example

<?php

// outputs e.g.  somefile.txt was last changed: December 29 2002 22:16:23.

$filename 'somefile.txt';
if (
file_exists($filename)) {
    echo 
"$filename was last changed: " date("F d Y H:i:s."filectime($filename));
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note:

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Note:

Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



filegroup

(PHP 4, PHP 5, PHP 7)

filegroupGets file group

Description

filegroup ( string $filename ) : int

Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

Parameters

filename

Path to the file.

Return Values

Returns the group ID of the file, or FALSE if an error occurs. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned.

Examples

Example #1 Finding the group of a file

<?php
$filename 
'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



fileinode

(PHP 4, PHP 5, PHP 7)

fileinodeGets file inode

Description

fileinode ( string $filename ) : int

Gets the file inode.

Parameters

filename

Path to the file.

Return Values

Returns the inode number of the file, or FALSE on failure.

Examples

Example #1 Comparing the inode of a file with the current file

<?php
$filename 
'index.php';
if (
getmyinode() == fileinode($filename)) {
    echo 
'You are checking the current file.';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • getmyinode() - Gets the inode of the current script
  • stat() - Gives information about a file



filemtime

(PHP 4, PHP 5, PHP 7)

filemtimeGets file modification time

Description

filemtime ( string $filename ) : int

This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.

Parameters

filename

Path to the file.

Return Values

Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

Examples

Example #1 filemtime() example

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename 'somefile.txt';
if (
file_exists($filename)) {
    echo 
"$filename was last modified: " date ("F d Y H:i:s."filemtime($filename));
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • filectime() - Gets inode change time of file
  • stat() - Gives information about a file
  • touch() - Sets access and modification time of file
  • getlastmod() - Gets time of last page modification



fileowner

(PHP 4, PHP 5, PHP 7)

fileownerGets file owner

Description

fileowner ( string $filename ) : int

Gets the file owner.

Parameters

filename

Path to the file.

Return Values

Returns the user ID of the owner of the file, or FALSE on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Examples

Example #1 Finding the owner of a file

<?php
$filename 
'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



fileperms

(PHP 4, PHP 5, PHP 7)

filepermsGets file permissions

Description

fileperms ( string $filename ) : int

Gets permissions for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod(), however on most platforms the return value will also include information on the type of file given as filename. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and macOS.

For local files, the specific return value is that of the st_mode member of the structure returned by the C library's stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required.

Examples

Example #1 Display permissions as an octal value

<?php
echo substr(sprintf('%o'fileperms('/tmp')), -4);
echo 
substr(sprintf('%o'fileperms('/etc/passwd')), -4);
?>

The above example will output:

   1777
   0644
   

Example #2 Display full permissions

<?php
$perms 
fileperms('/etc/passwd');

switch (
$perms 0xF000) {
    case 
0xC000// socket
        
$info 's';
        break;
    case 
0xA000// symbolic link
        
$info 'l';
        break;
    case 
0x8000// regular
        
$info 'r';
        break;
    case 
0x6000// block special
        
$info 'b';
        break;
    case 
0x4000// directory
        
$info 'd';
        break;
    case 
0x2000// character special
        
$info 'c';
        break;
    case 
0x1000// FIFO pipe
        
$info 'p';
        break;
    default: 
// unknown
        
$info 'u';
}

// Owner
$info .= (($perms 0x0100) ? 'r' '-');
$info .= (($perms 0x0080) ? 'w' '-');
$info .= (($perms 0x0040) ?
            ((
$perms 0x0800) ? 's' 'x' ) :
            ((
$perms 0x0800) ? 'S' '-'));

// Group
$info .= (($perms 0x0020) ? 'r' '-');
$info .= (($perms 0x0010) ? 'w' '-');
$info .= (($perms 0x0008) ?
            ((
$perms 0x0400) ? 's' 'x' ) :
            ((
$perms 0x0400) ? 'S' '-'));

// World
$info .= (($perms 0x0004) ? 'r' '-');
$info .= (($perms 0x0002) ? 'w' '-');
$info .= (($perms 0x0001) ?
            ((
$perms 0x0200) ? 't' 'x' ) :
            ((
$perms 0x0200) ? 'T' '-'));

echo 
$info;
?>

The above example will output:

   -rw-r--r--
   

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



filesize

(PHP 4, PHP 5, PHP 7)

filesizeGets file size

Description

filesize ( string $filename ) : int

Gets the size for the given file.

Parameters

filename

Path to the file.

Return Values

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename 'somefile.txt';
echo 
$filename ': ' filesize($filename) . ' bytes';

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



filetype

(PHP 4, PHP 5, PHP 7)

filetypeGets file type

Description

filetype ( string $filename ) : string

Returns the type of the given file.

Parameters

filename

Path to the file.

Return Values

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.

Returns FALSE if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Examples

Example #1 filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link
  • file_exists() - Checks whether a file or directory exists
  • mime_content_type() - Detect MIME Content-type for a file
  • pathinfo() - Returns information about a file path
  • stat() - Gives information about a file



flock

(PHP 4, PHP 5, PHP 7)

flockPortable advisory file locking

Description

flock ( resource $handle , int $operation [, int &$wouldblock ] ) : bool

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled with the LOCK_NB option documented below.

Parameters

handle

A file system pointer resource that is typically created using fopen().

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations, if flock() should not block during the locking attempt.

wouldblock

The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.5.22, 5.6.6 Added support for the wouldblock parameter on Windows.
5.3.2 The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

Examples

Example #1 flock() example

<?php

$fp 
fopen("/tmp/lock.txt""r+");

if (
flock($fpLOCK_EX)) {  // acquire an exclusive lock
    
ftruncate($fp0);      // truncate file
    
fwrite($fp"Write something here\n");
    
fflush($fp);            // flush output before releasing the lock
    
flock($fpLOCK_UN);    // release the lock
} else {
    echo 
"Couldn't get the lock!";
}

fclose($fp);

?>

Example #2 flock() using the LOCK_NB option

<?php
$fp 
fopen('/tmp/lock.txt''r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fpLOCK_EX LOCK_NB)) {
    echo 
'Unable to obtain lock';
    exit(-
1);
}

/* ... */

fclose($fp);
?>

Notes

Note:

flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.

Note:

Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

Note:

May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.

Warning

Assigning another value to handle argument in subsequent code will release the lock.

Warning

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under these environments.



fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fnmatchMatch filename against a pattern

Description

fnmatch ( string $pattern , string $string [, int $flags = 0 ] ) : bool

fnmatch() checks if the passed string would match the given shell wildcard pattern.

Parameters

pattern

The shell wildcard pattern.

string

The tested string. This function is especially useful for filenames, but may also be used on regular strings.

The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.
A list of possible flags for fnmatch()
Flag Description
FNM_NOESCAPE Disable backslash escaping.
FNM_PATHNAME Slash in string only matches slash in the given pattern.
FNM_PERIOD Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD Caseless match. Part of the GNU extension.

Return Values

Returns TRUE if there is a match, FALSE otherwise.

Changelog

Version Description
5.3.0 This function is now available on Windows platforms.

Examples

Example #1 Checking a color name against a shell wildcard pattern

<?php
if (fnmatch("*gr[ae]y"$color)) {
  echo 
"some form of gray ...";
}
?>

Notes

Warning

For now, this function is not available on non-POSIX compliant systems except Windows.

See Also

  • glob() - Find pathnames matching a pattern
  • preg_match() - Perform a regular expression match
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string



fopen

(PHP 4, PHP 5, PHP 7)

fopenOpens file or URL

Description

fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource

fopen() binds a named resource, specified by filename, to a stream.

Parameters

filename

If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode or open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$handle 
fopen("c:\\folder\\resource.txt""r");
?>

mode

The mode parameter specifies the type of access you require to the stream. It may be any of the following:
A list of possible modes for fopen() using mode
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the same behavior as 'x'.
'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'e' Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

The default translation mode is 'b'. You can use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the 'b' in all other cases.

If you specify the 't' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns a file pointer resource on success, or FALSE on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Changelog

Version Description
7.0.16, 7.1.2 The 'e' option was added.
5.2.6 The 'c' and 'c+' options were added

Examples

Example #1 fopen() examples

<?php
$handle 
fopen("/home/rasmus/file.txt""r");
$handle fopen("/home/rasmus/file.gif""wb");
$handle fopen("http://www.example.com/""r");
$handle fopen("ftp://user:password@example.com/somefile.txt""w");
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

Note:

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

Note:

This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen().

See Also



fpassthru

(PHP 4, PHP 5, PHP 7)

fpassthruOutput all remaining data on a file pointer

Description

fpassthru ( resource $handle ) : int

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Values

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

Examples

Example #1 Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name './img/ok.png';
$fp fopen($name'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

Notes

Note:

When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().

You are encouraged to use the b flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.

See Also



fputcsv

(PHP 5 >= 5.1.0, PHP 7)

fputcsvFormat line as CSV and write to file pointer

Description

fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\\" ]]] ) : int

fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated by a newline) to the specified file handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

fields

An array of strings.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

escape_char

The optional escape_char parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Note:

If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_char.

Return Values

Returns the length of the written string or FALSE on failure.

Changelog

Version Description
7.4.0 The escape_char parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.5.4 The escape_char parameter was added

Examples

Example #1 fputcsv() example

<?php

$list 
= array (
    array(
'aaa''bbb''ccc''dddd'),
    array(
'123''456''789'),
    array(
'"aaa"''"bbb"')
);

$fp fopen('file.csv''w');

foreach (
$list as $fields) {
    
fputcsv($fp$fields);
}

fclose($fp);
?>

The above example will write the following to file.csv:

   aaa,bbb,ccc,dddd
   123,456,789
   """aaa""","""bbb"""
   
   

Notes

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

See Also

  • fgetcsv() - Gets line from file pointer and parse for CSV fields



fputs

(PHP 4, PHP 5, PHP 7)

fputsAlias of fwrite()

Description

This function is an alias of: fwrite().



fread

(PHP 4, PHP 5, PHP 7)

freadBinary-safe file read

Description

fread ( resource $handle , int $length ) : string

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

Parameters

handle

A file system pointer resource that is typically created using fopen().

length

Up to length number of bytes read.

Return Values

Returns the read string or FALSE on failure.

Examples

Example #1 A simple fread() example

<?php
// get contents of a file into a string
$filename "/usr/local/something.txt";
$handle fopen($filename"r");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename 
"c:\\files\\somepic.gif";
$handle fopen($filename"rb");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle fopen("http://www.example.com/""rb");
$contents stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle 
fopen("http://www.example.com/""rb");
if (
FALSE === $handle) {
    exit(
"Failed to open stream to URL");
}

$contents '';

while (!
feof($handle)) {
    
$contents .= fread($handle8192);
}
fclose($handle);
?>

Notes

Note:

If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.

Note:

Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

See Also

  • fwrite() - Binary-safe file write
  • fopen() - Opens file or URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Opens process file pointer
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fscanf() - Parses input from a file according to a format
  • file() - Reads entire file into an array
  • fpassthru() - Output all remaining data on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer
  • unpack() - Unpack data from binary string



fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fscanfParses input from a file according to a format

Description

fscanf ( resource $handle , string $format [, mixed &$... ] ) : mixed

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream.

Each call to fscanf() reads one line from the file.

Parameters

handle

A file system pointer resource that is typically created using fopen().

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) Pads the result with spaces. This is the default.
0 Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier Description
% A literal percent character. No argument is required.
b The argument is treated as an integer and presented as a binary number.
c The argument is treated as an integer and presented as the character with that ASCII.
d The argument is treated as an integer and presented as a (signed) decimal number.
e The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f The argument is treated as a float and presented as a floating-point number (locale aware).
F The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G Like the g specifier but uses E and f.
o The argument is treated as an integer and presented as an octal number.
s The argument is treated and presented as a string.
u The argument is treated as an integer and presented as an unsigned decimal number.
x The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:
Type Handling
Type Specifiers
string s
integer d, u, c, o, x, X, b
double g, G, e, E, f, F

...

The optional assigned values.

Return Values

If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Examples

Example #1 fscanf() Example

<?php
$handle 
fopen("users.txt""r");
while (
$userinfo fscanf($handle"%s\t%s\t%s\n")) {
    list (
$name$profession$countrycode) = $userinfo;
    
//... do something with the values
}
fclose($handle);
?>

Example #2 Contents of users.txt

javier  argonaut        pe
   hiroshi sculptor        jp
   robert  slacker us
   luigi   florist it

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string



fseek

(PHP 4, PHP 5, PHP 7)

fseekSeeks on a file pointer

Description

fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) : int

Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence.

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

Parameters

handle

A file system pointer resource that is typically created using fopen().

offset

The offset.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Return Values

Upon success, returns 0; otherwise, returns -1.

Examples

Example #1 fseek() example

<?php

$fp 
fopen('somefile.txt''r');

// read some data
$data fgets($fp4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp0);

?>

Notes

Note:

If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

Note:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

See Also

  • ftell() - Returns the current position of the file read/write pointer
  • rewind() - Rewind the position of a file pointer



fstat

(PHP 4, PHP 5, PHP 7)

fstatGets information about a file using an open file pointer

Description

fstat ( resource $handle ) : array

Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Parameters

handle

A file system pointer resource that is typically created using fopen().

Return Values

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Examples

Example #1 fstat() example

<?php

// open a file
$fp fopen("/etc/passwd""r");

// gather statistics
$fstat fstat($fp);

// close the file
fclose($fp);

// print only the associative part
print_r(array_slice($fstat13));

?>

The above example will output something similar to:

   Array
   (
       [dev] => 771
       [ino] => 488704
       [mode] => 33188
       [nlink] => 1
       [uid] => 0
       [gid] => 0
       [rdev] => 0
       [size] => 1114
       [atime] => 1061067181
       [mtime] => 1056136526
       [ctime] => 1056136526
       [blksize] => 4096
       [blocks] => 8
   )
   

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.



ftell

(PHP 4, PHP 5, PHP 7)

ftellReturns the current position of the file read/write pointer

Description

ftell ( resource $handle ) : int

Returns the position of the file pointer referenced by handle.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Return Values

Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 ftell() example

<?php

// opens a file and read some data
$fp fopen("/etc/passwd""r");
$data fgets($fp12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

See Also

  • fopen() - Opens file or URL
  • popen() - Opens process file pointer
  • fseek() - Seeks on a file pointer
  • rewind() - Rewind the position of a file pointer



ftruncate

(PHP 4, PHP 5, PHP 7)

ftruncateTruncates a file to a given length

Description

ftruncate ( resource $handle , int $size ) : bool

Takes the filepointer, handle, and truncates the file to length, size.

Parameters

handle

The file pointer.

Note:

The handle must be open for writing.

size

The size to truncate to.

Note:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 File truncation example

<?php
$filename 
'lorem_ipsum.txt';

$handle fopen($filename'r+');
ftruncate($handlerand(1filesize($filename)));
rewind($handle);
echo 
fread($handlefilesize($filename));
fclose($handle);
?>

Notes

Note:

The file pointer is not changed.

See Also



fwrite

(PHP 4, PHP 5, PHP 7)

fwriteBinary-safe file write

Description

fwrite ( resource $handle , string $string [, int $length ] ) : int

fwrite() writes the contents of string to the file stream pointed to by handle.

Parameters

handle

A file system pointer resource that is typically created using fopen().

string

The string that is to be written.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Return Values

fwrite() returns the number of bytes written, or FALSE on error.

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp$string) {
    for (
$written 0$written strlen($string); $written += $fwrite) {
        
$fwrite fwrite($fpsubstr($string$written));
        if (
$fwrite === false) {
            return 
$written;
        }
    }
    return 
$written;
}
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Note:

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp 
fopen('data.txt''w');
fwrite($fp'1');
fwrite($fp'23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

Examples

Example #1 A simple fwrite() example

<?php
$filename 
'test.txt';
$somecontent "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    
// In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    
if (!$handle fopen($filename'a')) {
         echo 
"Cannot open file ($filename)";
         exit;
    }

    
// Write $somecontent to our opened file.
    
if (fwrite($handle$somecontent) === FALSE) {
        echo 
"Cannot write to file ($filename)";
        exit;
    }

    echo 
"Success, wrote ($somecontent) to file ($filename)";

    
fclose($handle);

} else {
    echo 
"The file $filename is not writable";
}
?>

See Also



glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

globFind pathnames matching a pattern

Description

glob ( string $pattern [, int $flags = 0 ] ) : array

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Parameters

pattern

The pattern. No tilde expansion or parameter substitution is done.

Special characters:

  • * - Matches zero or more characters.
  • ? - Matches exactly one character (any character).
  • [...] - Matches one character from a group of characters. If the first character is !, matches any character not in the group.
  • \ - Escapes the following character, except when the GLOB_NOESCAPE flag is used.

flags

Valid flags:

  • GLOB_MARK - Adds a slash (a backslash on Windows) to each directory returned
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
  • GLOB_NOCHECK - Return the search pattern if no files matching it were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directory entries which match the pattern
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Note:

On some systems it is impossible to distinguish between empty match and an error.

Changelog

Version Description
5.1.0 GLOB_ERR was added

Examples

Example #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo 
"$filename size " filesize($filename) . "\n";
}
?>

The above example will output something similar to:

   funclist.txt size 44686
   funcsummary.txt size 267625
   quickref.txt size 137820
   

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: This function isn't available on some systems (e.g. old Sun OS).

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

See Also



is_dir

(PHP 4, PHP 5, PHP 7)

is_dirTells whether the filename is a directory

Description

is_dir ( string $filename ) : bool

Tells whether the given filename is a directory.

Parameters

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

Return Values

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Examples

Example #1 is_dir() example

<?php
var_dump
(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

   bool(false)
   bool(false)
   bool(true)
   

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • chdir() - Change directory
  • dir() - Return an instance of the Directory class
  • opendir() - Open directory handle
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link



is_executable

(PHP 4, PHP 5, PHP 7)

is_executableTells whether the filename is executable

Description

is_executable ( string $filename ) : bool

Tells whether the filename is executable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is executable, or FALSE on error.

Examples

Example #1 is_executable() example

<?php

$file 
'/home/vincent/somefile.sh';

if (
is_executable($file)) {
    echo 
$file.' is executable';
} else {
    echo 
$file.' is not executable';
}

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link



is_file

(PHP 4, PHP 5, PHP 7)

is_fileTells whether the filename is a regular file

Description

is_file ( string $filename ) : bool

Tells whether the given file is a regular file.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Examples

Example #1 is_file() example

<?php
var_dump
(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

The above example will output:

   bool(true)
   bool(false)
   

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • is_dir() - Tells whether the filename is a directory
  • is_link() - Tells whether the filename is a symbolic link




is_readable

(PHP 4, PHP 5, PHP 7)

is_readableTells whether a file exists and is readable

Description

is_readable ( string $filename ) : bool

Tells whether a file exists and is readable.

Parameters

filename

Path to the file.

Return Values

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Examples

Example #1 is_readable() example

<?php
$filename 
'test.txt';
if (
is_readable($filename)) {
    echo 
'The file is readable';
} else {
    echo 
'The file is not readable';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

Note:

The check is done using the real UID/GID instead of the effective one.

This function may return TRUE for directories. Use is_dir() to distinguish file and directory.

See Also



is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

is_uploaded_fileTells whether the file was uploaded via HTTP POST

Description

is_uploaded_file ( string $filename ) : bool

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 is_uploaded_file() example

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo 
"File "$_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo 
"Displaying contents\n";
   
readfile($_FILES['userfile']['tmp_name']);
} else {
   echo 
"Possible file upload attack: ";
   echo 
"filename '"$_FILES['userfile']['tmp_name'] . "'.";
}

?>

See Also



is_writable

(PHP 4, PHP 5, PHP 7)

is_writableTells whether the filename is writable

Description

is_writable ( string $filename ) : bool

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE if the filename exists and is writable.

Examples

Example #1 is_writable() example

<?php
$filename 
'test.txt';
if (
is_writable($filename)) {
    echo 
'The file is writable';
} else {
    echo 
'The file is not writable';
}
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also



is_writeable

(PHP 4, PHP 5, PHP 7)

is_writeableAlias of is_writable()

Description

This function is an alias of: is_writable().



lchgrp

(PHP 5 >= 5.1.3, PHP 7)

lchgrpChanges group ownership of symlink

Description

lchgrp ( string $filename , mixed $group ) : bool

Attempts to change the group of the symlink filename to group.

Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.

Parameters

filename

Path to the symlink.

group

The group specified by name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the group of a symbolic link

<?php
$target 
'output.php';
$link 'output.html';
symlink($target$link);

lchgrp($link8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also



lchown

(PHP 5 >= 5.1.3, PHP 7)

lchownChanges user ownership of symlink

Description

lchown ( string $filename , mixed $user ) : bool

Attempts to change the owner of the symlink filename to user user.

Only the superuser may change the owner of a symlink.

Parameters

filename

Path to the file.

user

User name or number.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the owner of a symbolic link

<?php
$target 
'output.php';
$link 'output.html';
symlink($target$link);

lchown($link8);
?>

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note: This function is not implemented on Windows platforms.

See Also




linkinfo

(PHP 4, PHP 5, PHP 7)

linkinfoGets information about a link

Description

linkinfo ( string $path ) : int

Gets information about a link.

This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h).

Parameters

path

Path to the link.

Return Values

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns a non-negative integer on success, -1 in case the link was not found, or FALSE if an open.base_dir violation occurs.

Changelog

Version Description
5.3.0 This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

See Also



lstat

(PHP 4, PHP 5, PHP 7)

lstatGives information about a file or symbolic link

Description

lstat ( string $filename ) : array

Gathers the statistics of the file or symbolic link named by filename.

Parameters

filename

Path to a file or a symbolic link.

Return Values

See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Examples

Example #1 Comparison of stat() and lstat()

<?php
symlink
('uploads.php''uploads');

// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>

The above example will output something similar to:

Information that differs between the two files.

   Array
   (
       [ino] => 97236376
       [mode] => 33188
       [size] => 34
       [atime] => 1223580003
       [mtime] => 1223581848
       [ctime] => 1223581848
       [blocks] => 8
   )
   

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • stat() - Gives information about a file



mkdir

(PHP 4, PHP 5, PHP 7)

mkdirMakes directory

Description

mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool

Attempts to create the directory specified by pathname.

Parameters

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Note:

mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

Allows the creation of nested directories specified in the pathname.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mkdir() example

<?php
mkdir
("/path/to/my/dir"0700);
?>

Example #2 mkdir() using the recursive parameter

<?php
// Desired folder structure
$structure './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter 
// to mkdir() must be specified.

if (!mkdir($structure0777true)) {
    die(
'Failed to create folders...');
}

// ...
?>

Errors/Exceptions

Emits an E_WARNING level error if the directory already exists.

Emits an E_WARNING level error if the relevant permissions prevent creating the directory.

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • rmdir() - Removes directory



move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

move_uploaded_fileMoves an uploaded file to a new location

Description

move_uploaded_file ( string $filename , string $destination ) : bool

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

Parameters

filename

The filename of the uploaded file.

destination

The destination of the moved file.

Return Values

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Examples

Example #1 Uploading multiple files

<?php
$uploads_dir 
'/uploads';
foreach (
$_FILES["pictures"]["error"] as $key => $error) {
    if (
$error == UPLOAD_ERR_OK) {
        
$tmp_name $_FILES["pictures"]["tmp_name"][$key];
        
// basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        
$name basename($_FILES["pictures"]["name"][$key]);
        
move_uploaded_file($tmp_name"$uploads_dir/$name");
    }
}
?>

Notes

Note:

move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.

Warning

If the destination file already exists, it will be overwritten.

See Also



parse_ini_file

(PHP 4, PHP 5, PHP 7)

parse_ini_fileParse a configuration file

Description

parse_ini_file ( string $filename [, bool $process_sections = FALSE [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) : array

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array.

The structure of the ini file is the same as the php.ini's.

Parameters

filename

The filename of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Changelog

Version Description
7.0.0 Hash marks (#) are no longer recognized as comments.
5.6.1 Added new INI_SCANNER_TYPED mode.
5.3.0 Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
5.2.7 On syntax error this function will return FALSE rather than an empty array.
5.2.4 Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.

Examples

Example #1 Contents of sample.ini

   ; This is a sample configuration file
   ; Comments start with ';', as in php.ini
   
   [first_section]
   one = 1
   five = 5
   animal = BIRD
   
   [second_section]
   path = "/usr/local/bin"
   URL = "http://www.example.com/~username"
   
   [third_section]
   phpversion[] = "5.0"
   phpversion[] = "5.1"
   phpversion[] = "5.2"
   phpversion[] = "5.3"
   
   urls[svn] = "http://svn.php.net"
   urls[git] = "http://git.php.net"
   

Example #2 parse_ini_file() example

Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example:

<?php

define
('BIRD''Dodo bird');

// Parse without sections
$ini_array parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array parse_ini_file("sample.ini"true);
print_r($ini_array);

?>

The above example will output something similar to:

   Array
   (
       [one] => 1
       [five] => 5
       [animal] => Dodo bird
       [path] => /usr/local/bin
       [URL] => http://www.example.com/~username
       [phpversion] => Array
           (
               [0] => 5.0
               [1] => 5.1
               [2] => 5.2
               [3] => 5.3
           )
   
       [urls] => Array
           (
               [svn] => http://svn.php.net
               [git] => http://git.php.net
           )
   
   )
   Array
   (
       [first_section] => Array
           (
               [one] => 1
               [five] => 5
               [animal] => Dodo bird
           )
   
       [second_section] => Array
           (
               [path] => /usr/local/bin
               [URL] => http://www.example.com/~username
           )
   
       [third_section] => Array
           (
               [phpversion] => Array
                   (
                       [0] => 5.0
                       [1] => 5.1
                       [2] => 5.2
                       [3] => 5.3
                   )
   
               [urls] => Array
                   (
                       [svn] => http://svn.php.net
                       [git] => http://git.php.net
                   )
   
           )
   
   )
   

Example #3 parse_ini_file() parsing a php.ini file

<?php
// A simple function used for comparing the results below
function yesno($expression)
{
    return(
$expression 'Yes' 'No');
}

// Get the path to php.ini using the php_ini_loaded_file() 
// function available as of PHP 5.2.4
$ini_path php_ini_loaded_file();

// Parse php.ini
$ini parse_ini_file($ini_path);

// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo 
'(loaded) magic_quotes_gpc = ' yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>

The above example will output something similar to:

   (parsed) magic_quotes_gpc = Yes
   (loaded) magic_quotes_gpc = Yes
   

Notes

Note:

This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files.

Note:

If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used (as of PHP 5.6.1). Characters ?{}|&~!()^" must not be used anywhere in the key and have a special meaning in the value.

Note:

Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored.

See Also



parse_ini_string

(PHP 5 >= 5.3.0, PHP 7)

parse_ini_stringParse a configuration string

Description

parse_ini_string ( string $ini [, bool $process_sections = FALSE [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) : array

parse_ini_string() returns the settings in string ini in an associative array.

The structure of the ini string is the same as the php.ini's.

Parameters

ini

The contents of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible.

Return Values

The settings are returned as an associative array on success, and FALSE on failure.

Notes

Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used. Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also



pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pathinfoReturns information about a file path

Description

pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] ) : mixed

pathinfo() returns information about path: either an associative array or a string, depending on options.

Note:

For information on retrieving the current path info, read the section on predefined reserved variables.

Caution

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Parameters

path

The path to be parsed.

options

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

If options is not specified, returns all available elements.

Return Values

If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

Note:

If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below).

Note:

If the path does not have an extension, no extension element will be returned (see second example below).

Note:

If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty (see third example below).

If options is present, returns a string containing the requested element.

Changelog

Version Description
5.2.0 The PATHINFO_FILENAME constant was added.

Examples

Example #1 pathinfo() Example

<?php
$path_parts 
pathinfo('/www/htdocs/inc/lib.inc.php');

echo 
$path_parts['dirname'], "\n";
echo 
$path_parts['basename'], "\n";
echo 
$path_parts['extension'], "\n";
echo 
$path_parts['filename'], "\n"// since PHP 5.2.0
?>

The above example will output:

   /www/htdocs/inc
   lib.inc.php
   php
   lib.inc
   

Example #2 pathinfo() example showing difference between null and no extension

<?php
$path_parts 
pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);

$path_parts pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>

The above example will output something similar to:

   string(0) ""
   
   Notice: Undefined index: extension in test.php on line 6
   NULL
   

Example #3 pathinfo() example for a dot-file

<?php
print_r
(pathinfo('/some/path/.test'));
?>

The above example will output something similar to:

   Array
   (
       [dirname] => /some/path
       [basename] => .test
       [extension] => test
       [filename] => 
   )
   

See Also

  • dirname() - Returns a parent directory's path
  • basename() - Returns trailing name component of path
  • parse_url() - Parse a URL and return its components
  • realpath() - Returns canonicalized absolute pathname



pclose

(PHP 4, PHP 5, PHP 7)

pcloseCloses process file pointer

Description

pclose ( resource $handle ) : int

Closes a file pointer to a pipe opened by popen().

Parameters

handle

The file pointer must be valid, and must have been returned by a successful call to popen().

Return Values

Returns the termination status of the process that was run. In case of an error then -1 is returned.

Note:

If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.

Examples

Example #1 pclose() example

<?php
$handle 
popen('/bin/ls''r');
pclose($handle);
?>

Notes

Note: Unix Only:

pclose() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

See Also

  • popen() - Opens process file pointer



popen

(PHP 4, PHP 5, PHP 7)

popenOpens process file pointer

Description

popen ( string $command , string $mode ) : resource

Opens a pipe to a process executed by forking the command given by command.

Parameters

command

The command

mode

The mode

Return Values

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

If an error occurs, returns FALSE.

Examples

Example #1 popen() example

<?php
$handle 
popen("/bin/ls""r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #2 popen() example

<?php
error_reporting
(E_ALL);

/* Add redirection so we can get stderr. */
$handle popen('/path/to/executable 2>&1''r');
echo 
"'$handle'; " gettype($handle) . "\n";
$read fread($handle2096);
echo 
$read;
pclose($handle);
?>

Notes

Note:

If you're looking for bi-directional support (two-way), use proc_open().

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • pclose() - Closes process file pointer
  • fopen() - Opens file or URL
  • proc_open() - Execute a command and open file pointers for input/output



readfile

(PHP 4, PHP 5, PHP 7)

readfileOutputs a file

Description

readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int

Reads a file and writes it to the output buffer.

Parameters

filename

The filename being read.

use_include_path

You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.

context

A context stream resource.

Return Values

Returns the number of bytes read from the file on success, or FALSE on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 Forcing a download using readfile()

<?php
$file 
'monkey.gif';

if (
file_exists($file)) {
    
header('Content-Description: File Transfer');
    
header('Content-Type: application/octet-stream');
    
header('Content-Disposition: attachment; filename="'.basename($file).'"');
    
header('Expires: 0');
    
header('Cache-Control: must-revalidate');
    
header('Pragma: public');
    
header('Content-Length: ' filesize($file));
    
readfile($file);
    exit;
}
?>

The above example will output something similar to:

Open / Save dialogue

Notes

Note:

readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().

Tip

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

See Also




realpath_cache_get

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_getGet realpath cache entries

Description

realpath_cache_get ( void ) : array

Get the contents of the realpath cache.

Return Values

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

Examples

Example #1 realpath_cache_get() example

<?php
var_dump
(realpath_cache_get());
?>

The above example will output something similar to:

   array(2) {
     ["/test"]=>
     array(4) {
       ["key"]=>
       int(123456789)
       ["is_dir"]=>
       bool(true)
       ["realpath"]=>
       string(5) "/test"
       ["expires"]=>
       int(1260318939)
     }
     ["/test/test.php"]=>
     array(4) {
       ["key"]=>
       int(987654321)
       ["is_dir"]=>
       bool(false)
       ["realpath"]=>
       string(12) "/root/test.php"
       ["expires"]=>
       int(1260318939)
     }
   }
   

See Also



realpath_cache_size

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_sizeGet realpath cache size

Description

realpath_cache_size ( void ) : int

Get the amount of memory used by the realpath cache.

Return Values

Returns how much memory realpath cache is using.

Examples

Example #1 realpath_cache_size() example

<?php
var_dump
(realpath_cache_size());
?>

The above example will output something similar to:

   int(412)
   

See Also



realpath

(PHP 4, PHP 5, PHP 7)

realpathReturns canonicalized absolute pathname

Description

realpath ( string $path ) : string

realpath() expands all symbolic links and resolves references to /./, /../ and extra / characters in the input path and returns the canonicalized absolute pathname.

Parameters

path

The path being checked.

Note:

Whilst a path must be supplied, the value can be an empty string. In this case, the value is interpreted as the current directory.

Return Values

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, /./ or /../ components. Trailing delimiters, such as \ and /, are also removed.

realpath() returns FALSE on failure, e.g. if the file does not exist.

Note:

The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Note:

For case-insensitive filesystems realpath() may or may not normalize the character case.

Note:

The function realpath() will not work for a file which is inside a Phar as such path would be a virtual path, not a real one.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Changelog

Version Description
5.3.0 Prior to this release, if only the last path component did not exist, realpath() would not fail on *BSD systems. realpath() now fails in this case.
5.2.1 Prior to this version, realpath() returned FALSE if path is an empty string or NULL.

Examples

Example #1 realpath() example

<?php
chdir
('/var/www/');
echo 
realpath('./../../etc/passwd') . PHP_EOL;

echo 
realpath('/tmp/') . PHP_EOL;
?>

The above example will output:

   /etc/passwd
   /tmp
   

Example #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

<?php
echo realpath('/windows/system32'), PHP_EOL;

echo 
realpath('C:\Program Files\\'), PHP_EOL;
?>

The above example will output:

   C:\WINDOWS\System32
   C:\Program Files
   

See Also

  • basename() - Returns trailing name component of path
  • dirname() - Returns a parent directory's path
  • pathinfo() - Returns information about a file path



rename

(PHP 4, PHP 5, PHP 7)

renameRenames a file or directory

Description

rename ( string $oldname , string $newname [, resource $context ] ) : bool

Attempts to rename oldname to newname, moving it between directories if necessary. If renaming a file and newname exists, it will be overwritten. If renaming a directory and newname exists, this function will emit a warning.

Parameters

oldname

The old name.

Note:

The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.3.1 rename() can now rename files across drives in Windows.

Examples

Example #1 Example with rename()

<?php
rename
("/tmp/tmp_file.txt""/home/user/login/docs/my_file.txt");
?>

See Also



rewind

(PHP 4, PHP 5, PHP 7)

rewindRewind the position of a file pointer

Description

rewind ( resource $handle ) : bool

Sets the file position indicator for handle to the beginning of the file stream.

Note:

If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file pointer position.

Parameters

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rewind() overwriting example

<?php
$handle 
fopen('output.txt''r+');

fwrite($handle'Really long sentence.');
rewind($handle);
fwrite($handle'Foo');
rewind($handle);

echo 
fread($handlefilesize('output.txt'));

fclose($handle);
?>

The above example will output something similar to:

   Foolly long sentence.
   

See Also

  • fread() - Binary-safe file read
  • fseek() - Seeks on a file pointer
  • ftell() - Returns the current position of the file read/write pointer
  • fwrite() - Binary-safe file write



rmdir

(PHP 4, PHP 5, PHP 7)

rmdirRemoves directory

Description

rmdir ( string $dirname [, resource $context ] ) : bool

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    
mkdir('examples');
}

rmdir('examples');
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also



set_file_buffer

(PHP 4, PHP 5, PHP 7)

set_file_bufferAlias of stream_set_write_buffer()

Description

This function is an alias of: stream_set_write_buffer().



stat

(PHP 4, PHP 5, PHP 7)

statGives information about a file

Description

stat ( string $filename ) : array

Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink. Prior to PHP 7.4.0, on Windows NTS builds the size, atime, mtime and ctime statistics have been from the symlink, in this case.

lstat() is identical to stat() except it would instead be based off the symlinks status.

Parameters

filename

Path to the file.

Return Values

stat() and fstat() result format
Numeric Associative Description
0 dev device number ***
1 ino inode number ****
2 mode inode protection mode
3 nlink number of links
4 uid userid of owner *
5 gid groupid of owner *
6 rdev device type, if inode device
7 size size in bytes
8 atime time of last access (Unix timestamp)
9 mtime time of last modification (Unix timestamp)
10 ctime time of last inode change (Unix timestamp)
11 blksize blocksize of filesystem IO **
12 blocks number of 512-byte blocks allocated **

* On Windows this will always be 0.

** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

*** On Windows, as of PHP 7.4.0, this is the serial number of the volume that contains the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was the numeric representation of the drive letter (e.g. 2 for C:) for stat(), and 0 for lstat().

**** On Windows, as of PHP 7.4.0, this is the identifier associated with the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was always 0.

The value of mode contains information read by several functions. When written in octal, starting from the right, the first three digits are returned by chmod(). The next digit is ignored by PHP. The next two digits indicate the file type:
mode file types
mode in octal Meaning
0120000 link
0100000 regular file
0060000 block device
0040000 directory
0010000 fifo
So for example a regular file could be 0100644 and a directory could be 0040755.

In case of error, stat() returns FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Changelog

Version Description
7.4.0 On Windows, the device number is now the serial number of the volume that contains the file, and the inode number is the identifier associated with the file.
7.4.0 The size, atime, mtime and ctime statistics of symlinks are always those of the target. This was previously not the case for NTS builds on Windows.

Examples

Example #1 stat() example

<?php
/* Get file stat */
$stat stat('C:\php\php.exe');

/*
 * Print file access time, this is the same 
 * as calling fileatime()
 */
echo 'Access time: ' $stat['atime'];

/*
 * Print file modification time, this is the 
 * same as calling filemtime()
 */
echo 'Modification time: ' $stat['mtime'];

/* Print the device number */
echo 'Device number: ' $stat['dev'];
?>

Example #2 Using stat() information together with touch()

<?php
/* Get file stat */
$stat stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
    echo 
'stat() call failed...';
} else {
    
/*
     * We want the access time to be 1 week 
     * after the current access time.
     */
    
$atime $stat['atime'] + 604800;

    
/* Touch the file */
    
if (!touch('some_file.txt'time(), $atime)) {
        echo 
'Failed to touch file...';
    } else {
        echo 
'touch() returned success...';
    }
}
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • lstat() - Gives information about a file or symbolic link
  • fstat() - Gets information about a file using an open file pointer
  • filemtime() - Gets file modification time
  • filegroup() - Gets file group




tempnam

(PHP 4, PHP 5, PHP 7)

tempnamCreate file with unique file name

Description

tempnam ( string $dir , string $prefix ) : string

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.

Parameters

dir

The directory where the temporary filename will be created.

prefix

The prefix of the generated temporary filename.

Note: Only the first 63 characters of the prefix are used. Windows even uses only the first three characters of the prefix.

Return Values

Returns the new temporary filename (with path), or FALSE on failure.

Examples

Example #1 tempnam() example

<?php
$tmpfname 
tempnam("/tmp""FOO");

$handle fopen($tmpfname"w");
fwrite($handle"writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Notes

Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir contains more than 65534 files.

See Also



tmpfile

(PHP 4, PHP 5, PHP 7)

tmpfileCreates a temporary file

Description

tmpfile ( void ) : resource

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle.

The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.

Caution

If the script terminates unexpectedly, the temporary file may not be deleted.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or FALSE on failure.

Examples

Example #1 tmpfile() example

<?php
$temp 
tmpfile();
fwrite($temp"writing to tempfile");
fseek($temp0);
echo 
fread($temp1024);
fclose($temp); // this removes the file
?>

The above example will output:

   writing to tempfile
   

See Also



touch

(PHP 4, PHP 5, PHP 7)

touchSets access and modification time of file

Description

touch ( string $filename [, int $time = time() [, int $atime ]] ) : bool

Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it will be created.

Parameters

filename

The name of the file being touched.

time

The touch time. If time is not supplied, the current system time is used.

atime

If present, the access time of the given filename is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither are present, the current system time is used.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version Description
5.3.0 It became possible to change the modification time of a directory under Windows.

Examples

Example #1 touch() example

<?php
if (touch($filename)) {
    echo 
$filename ' modification time has been changed to present time';
} else {
    echo 
'Sorry, could not change modification time of ' $filename;
}
?>

Example #2 touch() using the time parameter

<?php
// This is the touch time, we'll set it to one hour in the past.
$time time() - 3600;

// Touch the file
if (!touch('some_file.txt'$time)) {
    echo 
'Whoops, something went wrong...';
} else {
    echo 
'Touched file with success';
}
?>

Notes

Note:

Note that time resolution may differ from one file system to another.

Warning

Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.



umask

(PHP 4, PHP 5, PHP 7)

umaskChanges the current umask

Description

umask ([ int $mask ] ) : int

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

Parameters

mask

The new umask.

Return Values

umask() without arguments simply returns the current umask otherwise the old umask is returned.

Examples

Example #1 umask() example

<?php
$old 
umask(0);
chmod("/path/some_dir/some_file.txt"0755);
umask($old);

// Checking
if ($old != umask()) {
    die(
'An error occurred while changing back the umask');
}
?>

Notes

Note:

Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.



Table of Contents

  • basename — Returns trailing name component of path
  • chgrp — Changes file group
  • chmod — Changes file mode
  • chown — Changes file owner
  • clearstatcache — Clears file status cache
  • copy — Copies file
  • delete — See unlink or unset
  • dirname — Returns a parent directory's path
  • disk_free_space — Returns available space on filesystem or disk partition
  • disk_total_space — Returns the total size of a filesystem or disk partition
  • diskfreespace — Alias of disk_free_space
  • fclose — Closes an open file pointer
  • feof — Tests for end-of-file on a file pointer
  • fflush — Flushes the output to a file
  • fgetc — Gets character from file pointer
  • fgetcsv — Gets line from file pointer and parse for CSV fields
  • fgets — Gets line from file pointer
  • fgetss — Gets line from file pointer and strip HTML tags
  • file_exists — Checks whether a file or directory exists
  • file_get_contents — Reads entire file into a string
  • file_put_contents — Write data to a file
  • file — Reads entire file into an array
  • fileatime — Gets last access time of file
  • filectime — Gets inode change time of file
  • filegroup — Gets file group
  • fileinode — Gets file inode
  • filemtime — Gets file modification time
  • fileowner — Gets file owner
  • fileperms — Gets file permissions
  • filesize — Gets file size
  • filetype — Gets file type
  • flock — Portable advisory file locking
  • fnmatch — Match filename against a pattern
  • fopen — Opens file or URL
  • fpassthru — Output all remaining data on a file pointer
  • fputcsv — Format line as CSV and write to file pointer
  • fputs — Alias of fwrite
  • fread — Binary-safe file read
  • fscanf — Parses input from a file according to a format
  • fseek — Seeks on a file pointer
  • fstat — Gets information about a file using an open file pointer
  • ftell — Returns the current position of the file read/write pointer
  • ftruncate — Truncates a file to a given length
  • fwrite — Binary-safe file write
  • glob — Find pathnames matching a pattern
  • is_dir — Tells whether the filename is a directory
  • is_executable — Tells whether the filename is executable
  • is_file — Tells whether the filename is a regular file
  • is_link — Tells whether the filename is a symbolic link
  • is_readable — Tells whether a file exists and is readable
  • is_uploaded_file — Tells whether the file was uploaded via HTTP POST
  • is_writable — Tells whether the filename is writable
  • is_writeable — Alias of is_writable
  • lchgrp — Changes group ownership of symlink
  • lchown — Changes user ownership of symlink
  • link — Create a hard link
  • linkinfo — Gets information about a link
  • lstat — Gives information about a file or symbolic link
  • mkdir — Makes directory
  • move_uploaded_file — Moves an uploaded file to a new location
  • parse_ini_file — Parse a configuration file
  • parse_ini_string — Parse a configuration string
  • pathinfo — Returns information about a file path
  • pclose — Closes process file pointer
  • popen — Opens process file pointer
  • readfile — Outputs a file
  • readlink — Returns the target of a symbolic link
  • realpath_cache_get — Get realpath cache entries
  • realpath_cache_size — Get realpath cache size
  • realpath — Returns canonicalized absolute pathname
  • rename — Renames a file or directory
  • rewind — Rewind the position of a file pointer
  • rmdir — Removes directory
  • set_file_buffer — Alias of stream_set_write_buffer
  • stat — Gives information about a file
  • symlink — Creates a symbolic link
  • tempnam — Create file with unique file name
  • tmpfile — Creates a temporary file
  • touch — Sets access and modification time of file
  • umask — Changes the current umask
  • unlink — Deletes a file



Inotify


Introduction

The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().

As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.



Installing/Configuring

Table of Contents


Requirements

This extension requires Linux 2.6.13 or newer, and a recent libC.



Installing/Configuring

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/inotify.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension defines a stream resource returned by inotify_init().




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Inotify constants usable with inotify_add_watch() and/or returned by inotify_read()
IN_ACCESS (integer)
File was accessed (read) (*)
IN_MODIFY (integer)
File was modified (*)
IN_ATTRIB (integer)
Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE (integer)
File opened for writing was closed (*)
IN_CLOSE_NOWRITE (integer)
File not opened for writing was closed (*)
IN_OPEN (integer)
File was opened (*)
IN_MOVED_TO (integer)
File moved into watched directory (*)
IN_MOVED_FROM (integer)
File moved out of watched directory (*)
IN_CREATE (integer)
File or directory created in watched directory (*)
IN_DELETE (integer)
File or directory deleted in watched directory (*)
IN_DELETE_SELF (integer)
Watched file or directory was deleted
IN_MOVE_SELF (integer)
Watch file or directory was moved
IN_CLOSE (integer)
Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE (integer)
Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS (integer)
Bitmask of all the above constants
IN_UNMOUNT (integer)
File system containing watched object was unmounted
IN_Q_OVERFLOW (integer)
Event queue overflowed (wd is -1 for this event)
IN_IGNORED (integer)
Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR (integer)
Subject of this event is a directory
IN_ONLYDIR (integer)
Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW (integer)
Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD (integer)
Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT (integer)
Monitor pathname for one event, then remove from watch list.

Note: The events marked with an asterisk (*) above can occur for files in watched directories.



Inotify Functions


inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watchAdd a watch to an initialized inotify instance

Description

inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask ) : int

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname.

Using inotify_add_watch() on a watched object replaces the existing watch. Using the IN_MASK_ADD constant adds (OR) events to the existing watch.

Parameters

inotify_instance

Resource returned by inotify_init()

pathname

File or directory to watch

mask

Events to watch for. See Predefined Constants.

Return Values

The return value is a unique (inotify instance wide) watch descriptor.

See Also



inotify_init

(PECL inotify >= 0.1.2)

inotify_initInitialize an inotify instance

Description

inotify_init ( void ) : resource

Initialize an inotify instance for use with inotify_add_watch()

Return Values

A stream resource or FALSE on error.

Examples

Example #1 Example usage of inotify

<?php
// Open an inotify instance
$fd inotify_init();

// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor inotify_add_watch($fd__FILE__IN_ATTRIB);

// generate an event
touch(__FILE__);

// Read events
$events inotify_read($fd);
print_r($events);

// The following methods allows to use inotify functions without blocking on inotify_read():

// - Using stream_select() on $fd:
$read = array($fd);
$write null;
$except null;
stream_select($read,$write,$except,0);

// - Using stream_set_blocking() on $fd
stream_set_blocking($fd0);
inotify_read($fd); // Does no block, and return false if no events are pending

// - Using inotify_queue_len() to check if event queue is not empty
$queue_len inotify_queue_len($fd); // If > 0, inotify_read() will not block

// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd$watch_descriptor);

// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);

?>

The above example will output something similar to:

   array(
     array(
       'wd' => 1,     // Equals $watch_descriptor
       'mask' => 4,   // IN_ATTRIB bit is set
       'cookie' => 0, // unique id to connect related events (e.g. 
                      // IN_MOVE_FROM and IN_MOVE_TO events)
       'name' => '',  // the name of a file (e.g. if we monitored changes
                      // in a directory)
     ),
   );
   

See Also



inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_lenReturn a number upper than zero if there are pending events

Description

inotify_queue_len ( resource $inotify_instance ) : int

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

Returns a number upper than zero if there are pending events.

See Also

  • inotify_init() - Initialize an inotify instance
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream



inotify_read

(PECL inotify >= 0.1.2)

inotify_readRead events from an inotify instance

Description

inotify_read ( resource $inotify_instance ) : array

Read inotify events from an inotify instance.

Parameters

inotify_instance

Resource returned by inotify_init()

Return Values

An array of inotify events or FALSE if no events was pending and inotify_instance is non-blocking. Each event is an array with the following keys:

  • wd is a watch descriptor returned by inotify_add_watch()
  • mask is a bit mask of events
  • cookie is a unique id to connect related events (e.g. IN_MOVE_FROM and IN_MOVE_TO)
  • name is the name of a file (e.g. if a file was modified in a watched directory)

See Also



inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watchRemove an existing watch from an inotify instance

Description

inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor ) : bool

inotify_rm_watch() removes the watch watch_descriptor from the inotify instance inotify_instance.

Parameters

inotify_instance

Resource returned by inotify_init()

watch_descriptor

Watch to remove from the instance

Return Values

Returns TRUE on success or FALSE on failure.

See Also


Table of Contents




Mimetype


Introduction

Warning

This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.



Installing/Configuring

Table of Contents


Requirements

No external libraries are needed to build this extension.



Installation

Warning

Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.

You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.

Note:

This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.

Note: Note to Win32 Users

In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.

Example #1 Setting the path to magic.mime

   mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"
   

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mimetype configuration options
Name Default Changeable Changelog
mime_magic.debug "0" PHP_INI_SYSTEM Available since PHP 5.0.0.
mime_magic.magicfile "/path/to/php/magic.mime" PHP_INI_SYSTEM Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.



Resource Types

This extension has no resource types defined.




Predefined Constants

This extension has no constants defined.




Phdfs


The phdfs extensions is using PHP to manipulate Hadoop HDFS phdfs requires PHP 5.3 or greater. Earlier versions may not work. For a quick start guide, please refer to the Tutorials section.



Installing/Configuring

Table of Contents


Requirements

PHP Version: PHP 5.3+

ZTS Enabled ( Thread Safety )

need to install hadoop



Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/phdfs.



This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

O_WRONLY (integer)
O_CREAT (integer)
O_APPEND (integer)



The phdfs class

(phdfs >= 0.1.0)

Introduction

Class synopsis

phdfs {
/* Properties */
static host ;
static port ;
/* Methods */
public connect ( void ) : bool
public __construct ( string $ip , string $port )
public copy ( string $source_file , string $destination_file ) : bool
public create_directory ( string $path ) : bool
public delete ( string $path ) : bool
public __destruct ( void ) : void
public disconnect ( void ) : bool
public exists ( string $path ) : bool
public file_info ( string $path ) : array
public list_directory ( string $path [, int $level = 0 ] ) : array
public read ( string $path [, int $length = 0 ] ) : string
public rename ( string $old_path , string $new_path ) : bool
public tell ( string $path [, int $read_length = 1024 ] ) : int
public write ( string $path , string $buffer [, int $mode = 0 ] ) : bool
}

Properties

host

port


phdfs::connect

(phdfs >= 0.1.0)

phdfs::connectDescription

Description

public phdfs::connect ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::__construct

(phdfs >= 0.1.0)

phdfs::__constructDescription

Description

public phdfs::__construct ( string $ip , string $port )

Warning

This function is currently not documented; only its argument list is available.

Parameters

ip

port

Return Values



phdfs::copy

(phdfs >= 0.1.0)

phdfs::copyDescription

Description

public phdfs::copy ( string $source_file , string $destination_file ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

source_file

destination_file

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::create_directory

(phdfs >= 0.1.0)

phdfs::create_directoryDescription

Description

public phdfs::create_directory ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::delete

(phdfs >= 0.1.0)

phdfs::deleteDescription

Description

public phdfs::delete ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::__destruct

(phdfs >= 0.1.0)

phdfs::__destructDescription

Description

public phdfs::__destruct ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

No value is returned.



phdfs::disconnect

(phdfs >= 0.1.0)

phdfs::disconnectDescription

Description

public phdfs::disconnect ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::exists

(phdfs>= 0.1.0)

phdfs::existsDescription

Description

public phdfs::exists ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::file_info

(phdfs >= 0.1.0)

phdfs::file_infoDescription

Description

public phdfs::file_info ( string $path ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns array on success or FALSE on failure.



phdfs::list_directory

(phdfs >= 0.1.0)

phdfs::list_directoryDescription

Description

public phdfs::list_directory ( string $path [, int $level = 0 ] ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

level

Return Values

Returns array on success or FALSE on failure.



phdfs::read

(phdfs >= 0.1.0)

phdfs::readDescription

Description

public phdfs::read ( string $path [, int $length = 0 ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

length

Return Values



phdfs::rename

(phdfs >= 0.1.0)

phdfs::renameDescription

Description

public phdfs::rename ( string $old_path , string $new_path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

old_path

new_path

Return Values

Returns TRUE on success or FALSE on failure.



phdfs::tell

(phdfs >= 0.1.0)

phdfs::tellDescription

Description

public phdfs::tell ( string $path [, int $read_length = 1024 ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

read_length

Return Values



phdfs::write

(phdfs >= 0.1.0)

phdfs::writeDescription

Description

public phdfs::write ( string $path , string $buffer [, int $mode = 0 ] ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

buffer

mode

Return Values

Returns TRUE on success or FALSE on failure.


Table of Contents




Proctitle


Introduction

This extension allows changing the current process', and thread, name on Linux and *BSD systems. This is useful when using pcntl_fork() to identify running processes in process list



Installing/Configuring

Table of Contents


Requirements

Nothing special.



Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/proctitle.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

This extension has no constants defined.



Proctitle Functions


setproctitle

(PECL proctitle >= 0.1.0)

setproctitleSet the process title

Description

setproctitle ( string $title ) : void

Sets the process title of the current process.

Parameters

title

The title to use as the process title.

Return Values

No value is returned.

Examples

Example #1 setproctitle() example

Running the example below will change the process title (visible with ps a for example).

<?php
setproctitle
("myscript");
?>

The above example will output something similar to:

   $ ps a
     PID TTY      STAT   TIME COMMAND
    1168 pts/3    S      0:00 myscript                                                                                                                         
   

See Also



setthreadtitle

(PECL proctitle >= 0.1.2)

setthreadtitleSet the thread title

Description

setthreadtitle ( string $title ) : bool

Sets the thread title.

Parameters

title

The title to use as the thread title.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 setthreadtitle() example

Running the example below will change the thread title (visible with ps c for example).

<?php
setthreadtitle
("myscript");
?>

The above example will output something similar to:

   $ ps c
     PID TTY      STAT   TIME COMMAND
    1178 pts/3    S      0:00 myscript
   

See Also


Table of Contents




xattr


Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.



Installing/Configuring

Table of Contents


Requirements

To use xattr, you will need libattr installed. It is available at » http://savannah.nongnu.org/projects/attr/.

Note:

These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.



Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/xattr.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XATTR_ROOT (integer)
Set attribute in root (trusted) namespace. Requires root privileges.
XATTR_DONTFOLLOW (integer)
Do not follow the symbolic link but operate on symbolic link itself.
XATTR_CREATE (integer)
Function will fail if extended attribute already exists.
XATTR_REPLACE (integer)
Function will fail if extended attribute doesn't exist.


xattr Functions


xattr_get

(PECL xattr >= 0.9.0)

xattr_get Get an extended attribute

Description

xattr_get ( string $filename , string $name [, int $flags = 0 ] ) : string

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns a string containing the value or FALSE if the attribute doesn't exist.

Examples

Example #1 Checks if system administrator has signed the file

<?php
$file 
'/usr/local/sbin/some_binary';
$signature xattr_get($file'Root signature'XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

See Also



xattr_list

(PECL xattr >= 0.9.0)

xattr_list Get a list of extended attributes

Description

xattr_list ( string $filename [, int $flags = 0 ] ) : array

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The path of the file.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

This function returns an array with names of extended attributes.

Examples

Example #1 Prints names of all extended attributes of file

<?php
$file 
'some_file';
$root_attributes xattr_list($fileXATTR_ROOT);
$user_attributes xattr_list($file);

echo 
"Root attributes: \n";
foreach (
$root_attributes as $attr_name) {
    
printf("%s\n"$attr_name);
}

echo 
"\n User attributes: \n";
foreach (
$attributes as $attr_name) {
    
printf("%s\n"$attr_name);
}

?>

See Also



xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove Remove an extended attribute

Description

xattr_remove ( string $filename , string $name [, int $flags = 0 ] ) : bool

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Removes all extended attributes of a file

<?php
$file 
'some_file';
$attributes xattr_list($file);

foreach (
$attributes as $attr_name) {
    
xattr_remove($file$attr_name);
}
?>

See Also



xattr_set

(PECL xattr >= 0.9.0)

xattr_set Set an extended attribute

Description

xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] ) : bool

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the flags parameter.

Parameters

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Supported xattr flags
XATTR_CREATE Function will fail if extended attribute already exists.
XATTR_REPLACE Function will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT Set attribute in root (trusted) namespace. Requires root privileges.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Sets extended attributes on .wav file

<?php
$file 
'my_favourite_song.wav';
xattr_set($file'Artist''Someone');
xattr_set($file'My ranking''Good');
xattr_set($file'Listen count''34');

/* ... other code ... */

printf("You've played this song %d times"xattr_get($file'Listen count')); 
?>

See Also



xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported Check if filesystem supports extended attributes

Description

xattr_supported ( string $filename [, int $flags = 0 ] ) : bool

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

Parameters

filename

The path of the tested file.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.

Return Values

This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).

Examples

Example #1 xattr_supported() example

The following code checks if we can use extended attributes.

<?php
$file 
'some_file';

if (
xattr_supported($file)) {
    
/* ... make use of some xattr_* functions ... */
}

?>

See Also


Table of Contents




xdiff


Introduction

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.



Installing/Configuring

Table of Contents


Requirements

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

Note:

You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.



Installation

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/xdiff.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XDIFF_PATCH_NORMAL (integer)
This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
XDIFF_PATCH_REVERSE (integer)
This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.


xdiff Functions


xdiff_file_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff_sizeRead a size of file created by applying a binary diff

Description

xdiff_file_bdiff_size ( string $file ) : int

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

Parameters

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$length 
xdiff_string_bdiff_size('file.bdiff');
echo 
"Resulting file will be $length bytes long";
?>

See Also



xdiff_file_bdiff

(PECL xdiff >= 1.5.0)

xdiff_file_bdiffMake binary diff of two files

Description

xdiff_file_bdiff ( string $old_file , string $new_file , string $dest ) : bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

<?php
$old_version 
'my_script_1.0.tgz';
$new_version 'my_script_1.1.tgz';

xdiff_file_bdiff($old_version$new_version'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also



xdiff_file_bpatch

(PECL xdiff >= 1.5.0)

xdiff_file_bpatchPatch a file with a binary diff

Description

xdiff_file_bpatch ( string $file , string $patch , string $dest ) : bool

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

<?php
$old_version 
'archive-1.0.tgz';
$patch 'archive.bpatch';

$result xdiff_file_bpatch($old_version$patch'archive-1.1.tgz');
if (
$result) {
   echo 
"File patched";
} else {
   echo 
"File couldn't be patched";
}

?>

Notes

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also



xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binaryAlias of xdiff_file_bdiff

Description

xdiff_file_diff_binary ( string $old_file , string $new_file , string $dest ) : bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version 
'my_script_1.0.tgz';
$new_version 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version$new_version'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also



xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diffMake unified diff of two files

Description

xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = FALSE ]] ) : bool

Makes an unified diff containing differences between old_file and new_file and stores it in dest file. The resulting file is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file.

context

Indicates how many lines of context you want to include in diff result.

minimal

Set this parameter to TRUE if you want to minimalize size of the result (can take a long time).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

<?php
$old_version 
'my_script.php';
$new_version 'my_new_script.php';

xdiff_file_diff($old_version$new_version'my_script.diff'2);
?>

Notes

Note:

This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

See Also



xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3Merge 3 files into one

Description

xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest ) : mixed

Merges three files into one and stores the result in a file dest. The old_file is an original version while new_file1 and new_file2 are modified versions of an original.

Parameters

old_file

Path to the first file. It acts as "old" file.

new_file1

Path to the second file. It acts as modified version of old_file.

new_file2

Path to the third file. It acts as modified version of old_file.

dest

Path of the resulting file, containing merged changed from both new_file1 and new_file2.

Return Values

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Examples

Example #1 xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version 
'original_script.php';
$fix1 'script_with_fix1.php';
$fix2 'script_with_fix2.php';

$errors xdiff_file_merge3($old_version$fix1$fix2'fixed_script.php');
if (
is_string($errors)) {
    echo 
"Rejects:\n";
    echo 
$errors;
}
?>

See Also



xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binaryAlias of xdiff_file_bpatch

Description

xdiff_file_patch_binary ( string $file , string $patch , string $dest ) : bool

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

Parameters

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version 
'archive-1.0.tgz';
$patch 'archive.bpatch';

$result xdiff_file_patch_binary($old_version$patch'archive-1.1.tgz');
if (
$result) {
   echo 
"File patched";
} else {
   echo 
"File couldn't be patched";
}

?>

Notes

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

See Also



xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patchPatch a file with an unified diff

Description

xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] ) : mixed

Patches a file with a patch and stores the result in a file. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation.

Parameters

file

The original file.

patch

The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

dest

Path of the resulting file.

flags

Can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

Return Values

Returns FALSE if an internal error happened, string with rejected chunks if patch couldn't be applied or TRUE if patch has been successfully applied.

Examples

Example #1 xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version 
'my_script-1.0.php';
$patch 'my_script.patch';

$errors xdiff_file_patch($old_version$patch'my_script-1.1.php');
if (
is_string($errors)) {
   echo 
"Rejects:\n";
   echo 
$errors;
}

?>

Example #2 Patch reversing example

The following code reverses a patch.

<?php
$new_version 
'my_script-1.1.php';
$patch 'my_script.patch';

$errors xdiff_file_patch($new_version$patch'my_script-1.0.php'XDIFF_PATCH_REVERSE);
if (
is_string($errors)) {
   echo 
"Rejects:\n";
   echo 
$errors;
}

?>

See Also



xdiff_file_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_file_rabdiffMake binary diff of two files using the Rabin's polynomial fingerprinting algorithm

Description

xdiff_file_rabdiff ( string $old_file , string $new_file , string $dest ) : bool

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

<?php
$old_version 
'my_script_1.0.tgz';
$new_version 'my_script_1.1.tgz';

xdiff_file_rabdiff($old_version$new_version'my_script.bdiff');
?>

Notes

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

See Also



xdiff_string_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff_sizeRead a size of file created by applying a binary diff

Description

xdiff_string_bdiff_size ( string $patch ) : int

Returns a size of a result file that would be created after applying binary patch to the original file.

Parameters

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Return Values

Returns the size of file that would be created.

Examples

Example #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$binary_patch 
file_get_contents('file.bdiff');
$length xdiff_string_bdiff_size($binary_patch);
echo 
"Resulting file will be $length bytes long";
?>

See Also



xdiff_string_bdiff

(PECL xdiff >= 1.5.0)

xdiff_string_bdiffMake binary diff of two strings

Description

xdiff_string_bdiff ( string $old_data , string $new_data ) : string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also



xdiff_string_bpatch

(PECL xdiff >= 1.5.0)

xdiff_string_bpatchPatch a string with a binary diff

Description

xdiff_string_bpatch ( string $str , string $patch ) : string

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also



xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binaryAlias of xdiff_string_bdiff

Description

xdiff_string_bdiff ( string $old_data , string $new_data ) : string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with result or FALSE if an internal error happened.

See Also



xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diffMake unified diff of two strings

Description

xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = FALSE ]] ) : string

Makes an unified diff containing differences between old_data string and new_data string and returns it. The resulting diff is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parameters

old_data

First string with data. It acts as "old" data.

new_data

Second string with data. It acts as "new" data.

context

Indicates how many lines of context you want to include in the diff result.

minimal

Set this parameter to TRUE if you want to minimalize the size of the result (can take a long time).

Return Values

Returns string with resulting diff or FALSE if an internal error happened.

Examples

Example #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article 
file_get_contents('./old_article.txt');
$new_article $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff xdiff_string_diff($old_article$new_article1);
if (
is_string($diff)) {
    echo 
"Differences between two articles:\n";
    echo 
$diff;
}

?>

Notes

Note:

This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

See Also



xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3Merge 3 strings into one

Description

xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] ) : mixed

Merges three strings into one and returns the result. The old_data is an original version of data while new_data1 and new_data2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

Parameters

old_data

First string with data. It acts as "old" data.

new_data1

Second string with data. It acts as modified version of old_data.

new_data2

Third string with data. It acts as modified version of old_data.

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

See Also



xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binaryAlias of xdiff_string_bpatch

Description

xdiff_string_patch_binary ( string $str , string $patch ) : string

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

Parameters

str

The original binary string.

patch

The binary patch string.

Return Values

Returns the patched string, or FALSE on error.

See Also



xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patchPatch a string with an unified diff

Description

xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] ) : string

Patches a str string with an unified patch in patch parameter and returns the result. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation. Any rejected parts of the patch will be stored inside error variable if it is provided.

Parameters

str

The original string.

patch

The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

flags

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

error

If provided then rejected parts are stored inside this variable.

Return Values

Returns the patched string, or FALSE on error.

Examples

Example #1 xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article 
file_get_contents('./old_article.txt');
$diff $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors '';

$new_article xdiff_string_patch($old_article$diffXDIFF_PATCH_NORMAL$errors);
if (
is_string($new_article)) {
    echo 
"New article:\n";
    echo 
$new_article;
}

if (
strlen($errors)) {
    echo 
"Rejects: \n";
    echo 
$errors;
}

?>

See Also



xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiffMake binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Description

xdiff_string_bdiff ( string $old_data , string $new_data ) : string

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parameters

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Return Values

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

See Also


Table of Contents





Human Language and Character Encoding Support


Enchant spelling library


Introduction

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchant supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)



Installing/Configuring

Table of Contents


Requirements

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later. Enchant 2.0.0 or later is not yet supported.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.



Installation

This extension is bundled with PHP as of PHP 5.3.0. Before this time, enchant was a PECL extension. Users of versions prior to 5.3.0 may use the » PECL extension.

Provided the required libraries are installed, users of PHP 5.3.0 or later may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.




Predefined Constants

ENCHANT_MYSPELL (integer)
Dictionary type for MySpell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path().
ENCHANT_ISPELL (integer)
Dictionary type for Ispell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path().



Examples

Example #1 Enchant Usage Example

<?php
$tag 
'en_US';
$r enchant_broker_init();
$bprovides enchant_broker_describe($r);
echo 
"Current broker provides the following backend(s):\n";
print_r($bprovides);

$dicts enchant_broker_list_dicts($r);
print_r($dicts);
if (
enchant_broker_dict_exists($r,$tag)) {
    
$d enchant_broker_request_dict($r$tag);
    
$dprovides enchant_dict_describe($d);
    echo 
"dictionary $tag provides:\n";
    
$wordcorrect enchant_dict_check($d"soong");
    
print_r($dprovides);
    if (!
$wordcorrect) {
        
$suggs enchant_dict_suggest($d"soong");
        echo 
"Suggestions for 'soong':";
        
print_r($suggs);
    }
    
enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>


Enchant Functions


enchant_broker_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0)

enchant_broker_describeEnumerates the Enchant providers

Description

enchant_broker_describe ( resource $broker ) : array

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parameters

broker

Broker resource

Return Values

Returns an array of available Enchant providers with their details, or FALSE on failure.

Examples

Example #1 List the backends provided by the given broker

<?php
$r 
enchant_broker_init();
$bprovides enchant_broker_describe($r);
echo 
"Current broker provides the following backend(s):\n";
print_r($bprovides);

?>

The above example will output something similar to:

   Current broker provides the following backend(s):
   Array
   (
       [0] => Array
           (
               [name] => aspell
               [desc] => Aspell Provider
               [file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [1] => Array
           (
               [name] => hspell
               [desc] => Hspell Provider
               [file] => /usr/lib/enchant/libenchant_hspell.so
           )
   
       [2] => Array
           (
               [name] => ispell
               [desc] => Ispell Provider
               [file] => /usr/lib/enchant/libenchant_ispell.so
           )
   
       [3] => Array
           (
               [name] => myspell
               [desc] => Myspell Provider
               [file] => /usr/lib/enchant/libenchant_myspell.so
           )
   
   )
   



enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_dict_existsWhether a dictionary exists or not. Using non-empty tag

Description

enchant_broker_dict_exists ( resource $broker , string $tag ) : bool

Tells if a dictionary exists or not, using a non-empty tags

Parameters

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Return Values

Returns TRUE when the tag exist or FALSE when not.

Examples

Example #1 A enchant_broker_dict_exists() example

<?php
$tag 
'en_US';
$r enchant_broker_init();
if (
enchant_broker_dict_exists($r,$tag)) {
    echo 
$tag " dictionary found.\n";
}
?>

See Also



enchant_broker_free_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_free_dictFree a dictionary resource

Description

enchant_broker_free_dict ( resource $dict ) : bool

Free a dictionary resource.

Parameters

dict

Dictionary resource.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



enchant_broker_free

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_freeFree the broker resource and its dictionaries

Description

enchant_broker_free ( resource $broker ) : bool

Free a broker resource with all its dictionaries.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

See Also



enchant_broker_get_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_get_dict_pathGet the directory path for a given backend

Description

enchant_broker_get_dict_path ( resource $broker , int $dict_type ) : bool

Get the directory path for a given backend.

Parameters

broker

Broker resource.

dict_type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

Return Values

Returns the path of the dictionary directory on success or FALSE on failure.

See Also



enchant_broker_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_get_errorReturns the last error of the broker

Description

enchant_broker_get_error ( resource $broker ) : string

Returns the last error which occurred in this broker.

Parameters

broker

Broker resource.

Return Values

Return the msg string if an error was found or FALSE



enchant_broker_init

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_initCreate a new broker object capable of requesting

Description

enchant_broker_init ( void ) : resource

Parameters

Return Values

Returns a broker resource on success or FALSE.

See Also



enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_list_dictsReturns a list of available dictionaries

Description

enchant_broker_list_dicts ( resource $broker ) : mixed

Returns a list of available dictionaries with their details.

Parameters

broker

Broker resource

Return Values

Returns an array of available dictionaries with their details, or FALSE on failure.

Examples

Example #1 List all available dictionaries for one broker

<?php
$r 
enchant_broker_init();
$dicts enchant_broker_list_dicts($r);
print_r($dicts);
?>

The above example will output something similar to:

   Array
   (
       [0] => Array
           (
               [lang_tag] => de
               [provider_name] => aspell
               [provider_desc] => Aspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [1] => Array
           (
               [lang_tag] => de_DE
               [provider_name] => aspell
               [provider_desc] => Aspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [3] => Array
           (
               [lang_tag] => en
               [provider_name] => aspell
               [provider_desc] => Aspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [4] => Array
           (
               [lang_tag] => en_GB
               [provider_name] => aspell
               [provider_desc] => Aspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [5] => Array
           (
               [lang_tag] => en_US
               [provider_name] => aspell
               [provider_desc] => Aspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_aspell.so
           )
   
       [6] => Array
           (
               [lang_tag] => hi_IN
               [provider_name] => myspell
               [provider_desc] => Myspell Provider
               [provider_file] => /usr/lib/enchant/libenchant_myspell.so
           )
   
   )
   

See Also



enchant_broker_request_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_dictCreate a new dictionary using a tag

Description

enchant_broker_request_dict ( resource $broker , string $tag ) : resource

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parameters

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Return Values

Returns a dictionary resource on success or FALSE on failure.

Examples

Example #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

<?php
$tag 
'en_US';
$broker enchant_broker_init();
if (
enchant_broker_dict_exists($broker,$tag)) {
    
$dict enchant_broker_request_dict($r$tag);
}
?>

See Also



enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dictCreates a dictionary using a PWL file

Description

enchant_broker_request_pwl_dict ( resource $broker , string $filename ) : resource

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Parameters

broker

Broker resource

filename

Path to the PWL file. If there is no such file, a new one will be created if possible.

Return Values

Returns a dictionary resource on success or FALSE on failure.

See Also



enchant_broker_set_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_set_dict_pathSet the directory path for a given backend

Description

enchant_broker_set_dict_path ( resource $broker , int $dict_type , string $value ) : bool

Set the directory path for a given backend.

Parameters

broker

Broker resource.

dict_type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

value

The path of the dictionary directory.

Return Values

Returns TRUE on success or FALSE on failure.

See Also



enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_set_orderingDeclares a preference of dictionaries to use for the language

Description

enchant_broker_set_ordering ( resource $broker , string $tag , string $ordering ) : bool

Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

Parameters

broker

Broker resource

tag

Language tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

ordering

Comma delimited list of provider names

Return Values

Returns TRUE on success or FALSE on failure.



enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personalAdd a word to personal word list

Description

enchant_dict_add_to_personal ( resource $dict , string $word ) : void

Add a word to personal word list of the given dictionary.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

Example #1 Adding a word to a PWL

<?php

$filename 
'./my_word_list.pwl';
$word 'Supercalifragilisticexpialidocious';

$broker enchant_broker_init();
$dict enchant_broker_request_pwl_dict($broker$filename);

enchant_dict_add_to_personal($dict$word);

enchant_broker_free($broker);

?>

See Also



enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_sessionAdd 'word' to this spell-checking session

Description

enchant_dict_add_to_session ( resource $dict , string $word ) : void

Add a word to the given dictionary. It will be added only for the active spell-checking session.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

No value is returned.

See Also



enchant_dict_check

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_checkCheck whether a word is correctly spelled or not

Description

enchant_dict_check ( resource $dict , string $word ) : bool

If the word is correctly spelled return TRUE, otherwise return FALSE

Parameters

dict

Dictionary resource

word

The word to check

Return Values

Returns TRUE if the word is spelled correctly, FALSE if not.



enchant_dict_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_describeDescribes an individual dictionary

Description

enchant_dict_describe ( resource $dict ) : mixed

Returns the details of the dictionary.

Parameters

dict

Dictionary resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag 
'en_US';
$broker enchant_broker_init();
if (
enchant_broker_dict_exists($broker,$tag)) {
    
$dict enchant_broker_request_dict($r$tag);
    
$dict_details enchant_dict_describe($dict);
    
print_r($dict_details);
}
?>

The above example will output something similar to:

   Array
   (
       [lang] => en_US
       [name] => aspell
       [desc] => Aspell Provider
       [file] => /usr/lib/enchant/libenchant_aspell.so
   )
   



enchant_dict_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_get_errorReturns the last error of the current spelling-session

Description

enchant_dict_get_error ( resource $dict ) : string

Returns the last error of the current spelling-session

Parameters

dict

Dictinaray resource

Return Values

Returns the error message as string or FALSE if no error occurred.



enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_is_in_sessionWhether or not 'word' exists in this spelling-session

Description

enchant_dict_is_in_session ( resource $dict , string $word ) : bool

Tells whether or not a word already exists in the current session.

Parameters

dict

Dictionary resource

word

The word to lookup

Return Values

Returns TRUE if the word exists or FALSE

See Also



enchant_dict_quick_check

(PHP 5 >= 5.3.0, PHP 7, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_checkCheck the word is correctly spelled and provide suggestions

Description

enchant_dict_quick_check ( resource $dict , string $word [, array &$suggestions ] ) : bool

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parameters

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Return Values

Returns TRUE if the word is correctly spelled or FALSE

Examples

Example #1 A enchant_dict_quick_check() example

<?php
$tag 
'en_US';
$r enchant_broker_init();

if (
enchant_broker_dict_exists($r,$tag)) {
    
$d enchant_broker_request_dict($r$tag);
    
enchant_dict_quick_check($d'soong'$suggs);
    
print_r($suggs);
}
?>

The above example will output something similar to:

   Array
   (
       [0] => song
       [1] => snog
       [2] => soon
       [3] => Sang
       [4] => Sung
       [5] => sang
       [6] => sung
       [7] => sponge
       [8] => spongy
       [9] => snag
       [10] => snug
       [11] => sonic
       [12] => sing
       [13] => songs
       [14] => Son
       [15] => Sonja
       [16] => Synge
       [17] => son
       [18] => Sejong
       [19] => sarong
       [20] => sooner
       [21] => Sony
       [22] => sown
       [23] => scone
       [24] => song's
   )
   

See Also



enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_store_replacementAdd a correction for a word

Description

enchant_dict_store_replacement ( resource $dict , string $mis , string $cor ) : void

Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.

Parameters

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Return Values

Returns TRUE on success or FALSE on failure.



enchant_dict_suggest

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_suggestWill return a list of values if any of those pre-conditions are not met

Description

enchant_dict_suggest ( resource $dict , string $word ) : array

Parameters

dict

Dictionary resource

word

Word to use for the suggestions.

Return Values

Will returns an array of suggestions if the word is bad spelled.

Examples

Example #1 A enchant_dict_suggest() example

<?php
$tag 
'en_US';
$r enchant_broker_init();
if (
enchant_broker_dict_exists($r,$tag)) {
    
$d enchant_broker_request_dict($r$tag);

    
$wordcorrect enchant_dict_check($d"soong");
    if (!
$wordcorrect) {
        
$suggs enchant_dict_suggest($d"soong");
        echo 
"Suggestions for 'soong':";
        
print_r($suggs);
    }
    
enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

See Also


Table of Contents




FriBiDi


Introduction

FriBiDi is a free implementation of the »  Unicode Bidirectional Algorithm.



Installing/Configuring

Table of Contents


Requirements

You must download and install the » FriBiDi package.



Installation

This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/fribidi.

In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.

Windows users will enable php_fribidi.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

FRIBIDI_CHARSET_UTF8 (integer)
Unicode
FRIBIDI_CHARSET_8859_6 (integer)
Arabic
FRIBIDI_CHARSET_8859_8 (integer)
Hebrew
FRIBIDI_CHARSET_CP1255 (integer)
Hebrew/Yiddish
FRIBIDI_CHARSET_CP1256 (integer)
Arabic
FRIBIDI_CHARSET_ISIRI_3342 (integer)
Persian
FRIBIDI_CHARSET_CAP_RTL (integer)
Used for test purposes, will treat CAPS as non-English letters
FRIBIDI_RTL (integer)
Right to left
FRIBIDI_LTR (integer)
Left to right
FRIBIDI_AUTO (integer)
Autodetect the base direction


FriBiDi Functions


fribidi_log2vis

(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)

fribidi_log2visConvert a logical string to a visual one

Description

fribidi_log2vis ( string $str , string $direction , int $charset ) : string

Converts a logical string to a visual one.

Parameters

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Return Values

Returns the visual string on success or FALSE on failure.


Table of Contents




Determine gender of firstnames


Introduction

Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.



Installing/Configuring

Table of Contents


Installation

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/gender.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.




Examples

Table of Contents


Usage example.

Gender class usage example.

Example #1 Usage example.

<?php

namespace Gender;

$gender = new Gender;

 
$name "Milene";
$country Gender::FRANCE;
 
$result $gender->get($name$country);

$data $gender->country($country);

switch(
$result) {
    case 
Gender::IS_FEMALE:
        
printf("The name %s is female in %s\n"$name$data['country']);
    break;

 
    case 
Gender::IS_MOSTLY_FEMALE:
        
printf("The name %s is mostly female in %s\n"$name$data['country']);
    break;

 
    case 
Gender::IS_MALE:
        
printf("The name %s is male in %s\n"$name$data['country']);
    break;

 
    case 
Gender::IS_MOSTLY_MALE:
        
printf("The name %s is mostly male in %s\n"$name$data['country']);
    break;

 
    case 
Gender::IS_UNISEX_NAME:
        
printf("The name %s is unisex in %s\n"$name$data['country']);
    break;

 
    case 
Gender::IS_A_COUPLE:
        
printf("The name %s is both male and female in %s\n"$name$data['country']);
    break;

 
    case 
Gender::NAME_NOT_FOUND:
        
printf("The name %s was not found for %s\n"$name$data['country']);
    break;

 
    case 
Gender::ERROR_IN_NAME:
        echo 
"There is an error in the given name!\n";
    break;
 
    default:
        echo 
"An error occurred!\n";
    break;

}



The Gender\Gender class

(PECL gender >= 0.6.0)

Introduction

Class synopsis

Gender\Gender {
/* Constants */
const integer IS_FEMALE = 70 ;
const integer IS_MOSTLY_FEMALE = 102 ;
const integer IS_MALE = 77 ;
const integer IS_MOSTLY_MALE = 109 ;
const integer IS_UNISEX_NAME = 63 ;
const integer IS_A_COUPLE = 67 ;
const integer NAME_NOT_FOUND = 32 ;
const integer ERROR_IN_NAME = 69 ;
const integer ANY_COUNTRY = 0 ;
const integer BRITAIN = 1 ;
const integer IRELAND = 2 ;
const integer USA = 3 ;
const integer SPAIN = 4 ;
const integer PORTUGAL = 5 ;
const integer ITALY = 6 ;
const integer MALTA = 7 ;
const integer FRANCE = 8 ;
const integer BELGIUM = 9 ;
const integer LUXEMBOURG = 10 ;
const integer NETHERLANDS = 11 ;
const integer GERMANY = 12 ;
const integer EAST_FRISIA = 13 ;
const integer AUSTRIA = 14 ;
const integer SWISS = 15 ;
const integer ICELAND = 16 ;
const integer DENMARK = 17 ;
const integer NORWAY = 18 ;
const integer SWEDEN = 19 ;
const integer FINLAND = 20 ;
const integer ESTONIA = 21 ;
const integer LATVIA = 22 ;
const integer LITHUANIA = 23 ;
const integer POLAND = 24 ;
const integer CZECH_REP = 25 ;
const integer SLOVAKIA = 26 ;
const integer HUNGARY = 27 ;
const integer ROMANIA = 28 ;
const integer BULGARIA = 29 ;
const integer BOSNIA = 30 ;
const integer CROATIA = 31 ;
const integer KOSOVO = 32 ;
const integer MACEDONIA = 33 ;
const integer MONTENEGRO = 34 ;
const integer SERBIA = 35 ;
const integer SLOVENIA = 36 ;
const integer ALBANIA = 37 ;
const integer GREECE = 38 ;
const integer RUSSIA = 39 ;
const integer BELARUS = 40 ;
const integer MOLDOVA = 41 ;
const integer UKRAINE = 42 ;
const integer ARMENIA = 43 ;
const integer AZERBAIJAN = 44 ;
const integer GEORGIA = 45 ;
const integer KAZAKH_UZBEK = 46 ;
const integer TURKEY = 47 ;
const integer ARABIA = 48 ;
const integer ISRAEL = 49 ;
const integer CHINA = 50 ;
const integer INDIA = 51 ;
const integer JAPAN = 52 ;
const integer KOREA = 53 ;
/* Methods */
public connect ( string $dsn ) : bool
public __construct ([ string $dsn ] )
public country ( int $country ) : array
public get ( string $name [, int $country ] ) : int
public isNick ( string $name0 , string $name1 [, int $country ] ) : array
public similarNames ( string $name [, int $country ] ) : array
}

Predefined Constants

Gender\Gender::IS_FEMALE

Gender\Gender::IS_MOSTLY_FEMALE

Gender\Gender::IS_MALE

Gender\Gender::IS_MOSTLY_MALE

Gender\Gender::IS_UNISEX_NAME

Gender\Gender::IS_A_COUPLE

Gender\Gender::NAME_NOT_FOUND

Gender\Gender::ERROR_IN_NAME

Gender\Gender::ANY_COUNTRY

Gender\Gender::BRITAIN

Gender\Gender::IRELAND

Gender\Gender::USA

Gender\Gender::SPAIN

Gender\Gender::PORTUGAL

Gender\Gender::ITALY

Gender\Gender::MALTA

Gender\Gender::FRANCE

Gender\Gender::BELGIUM

Gender\Gender::LUXEMBOURG

Gender\Gender::NETHERLANDS

Gender\Gender::GERMANY

Gender\Gender::EAST_FRISIA

Gender\Gender::AUSTRIA

Gender\Gender::SWISS

Gender\Gender::ICELAND

Gender\Gender::DENMARK

Gender\Gender::NORWAY

Gender\Gender::SWEDEN

Gender\Gender::FINLAND

Gender\Gender::ESTONIA

Gender\Gender::LATVIA

Gender\Gender::LITHUANIA

Gender\Gender::POLAND

Gender\Gender::CZECH_REP

Gender\Gender::SLOVAKIA

Gender\Gender::HUNGARY

Gender\Gender::ROMANIA

Gender\Gender::BULGARIA

Gender\Gender::BOSNIA

Gender\Gender::CROATIA

Gender\Gender::KOSOVO

Gender\Gender::MACEDONIA

Gender\Gender::MONTENEGRO

Gender\Gender::SERBIA

Gender\Gender::SLOVENIA

Gender\Gender::ALBANIA

Gender\Gender::GREECE

Gender\Gender::RUSSIA

Gender\Gender::BELARUS

Gender\Gender::MOLDOVA

Gender\Gender::UKRAINE

Gender\Gender::ARMENIA

Gender\Gender::AZERBAIJAN

Gender\Gender::GEORGIA

Gender\Gender::KAZAKH_UZBEK

Gender\Gender::TURKEY

Gender\Gender::ARABIA

Gender\Gender::ISRAEL

Gender\Gender::CHINA

Gender\Gender::INDIA

Gender\Gender::JAPAN

Gender\Gender::KOREA


Gender\Gender::connect

(PECL gender >= 0.6.0)

Gender\Gender::connectConnect to an external name dictionary

Description

public Gender\Gender::connect ( string $dsn ) : bool

Connect to an external name dictionary. Currently only streams are supported.

Parameters

dsn

DSN to open.

Return Values

Boolean as success of failure.



Gender\Gender::__construct

(PECL gender >= 0.6.0)

Gender\Gender::__constructConstruct the Gender object

Description

public Gender\Gender::__construct ([ string $dsn ] )

Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.

Parameters

dsn

DSN to open.

Return Values



Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::countryGet textual country representation

Description

public Gender\Gender::country ( int $country ) : array

Returns the textual representation of a country from a Gender class constant.

Parameters

country

A country ID specified by a Gender\Gender class constant.

Return Values

Returns an array with the short and full names of the country on success or FALSE on failure.

Examples

Example #1 Using Gender\Gender::country()

$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));

The above example will output:

   array(2) {
     'country_short' =>
     string(2) "UK"
     'country' =>
     string(13) "Great Britain"
   }
   



Gender\Gender::get

(PECL gender >= 0.6.0)

Gender\Gender::getGet gender of a name

Description

public Gender\Gender::get ( string $name [, int $country ] ) : int

Get the gender of the name in a particular country.

Parameters

name

Name to check.

country

Country id identified by Gender class constant.

Return Values

Returns gender of the name.



Gender\Gender::isNick

(PECL gender >= 0.9.0)

Gender\Gender::isNickCheck if the name0 is an alias of the name1

Description

public Gender\Gender::isNick ( string $name0 , string $name1 [, int $country ] ) : array

Check whether the name0 is a nick of the name1.

Parameters

name0

Name to check.

name1

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Return Values

Returns TRUE on success or FALSE on failure.



Gender\Gender::similarNames

(PECL gender >= 0.9.0)

Gender\Gender::similarNamesGet similar names

Description

public Gender\Gender::similarNames ( string $name [, int $country ] ) : array

Get similar names for the given name and country.

Parameters

name

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

Return Values

Returns an array with the similar names found.


Table of Contents




Gettext


Introduction

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at » http://www.gnu.org/software/gettext/manual/gettext.html.



Installing/Configuring

Table of Contents


Requirements

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html



Installation

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.



Runtime Configuration

This extension has no configuration directives defined in php.ini.



Resource Types

This extension has no resource types defined.




Predefined Constants

This extension has no constants defined.



Gettext Functions


bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

bind_textdomain_codesetSpecify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

bind_textdomain_codeset ( string $domain , string $codeset ) : string

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

Parameters

domain

The domain

codeset

The code set

Return Values

A string on success.



bindtextdomain

(PHP 4, PHP 5, PHP 7)

bindtextdomainSets the path for a domain

Description

bindtextdomain ( string $domain , string $directory ) : string

The bindtextdomain() function sets the path for a domain.

Parameters

domain

The domain

directory

The directory path

Return Values

The full pathname for the domain currently being set.

Examples

Example #1 bindtextdomain() example

<?php

$domain 
'myapp';
echo 
bindtextdomain($domain'/usr/share/myapp/locale');

?>

The above example will output:

   /usr/share/myapp/locale
   



dcgettext

(PHP 4, PHP 5, PHP 7)

dcgettextOverrides the domain for a single lookup

Description

dcgettext ( string $domain , string $message , int $category ) : string

This function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

category

The category

Return Values

A string on success.

See Also

  • gettext() - Lookup a message in the current domain



dcngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dcngettextPlural version of dcgettext

Description

dcngettext ( string $domain , string $msgid1 , string $msgid2 , int $n , int $category ) : string

This function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

category

Return Values

A string on success.

See Also



dgettext

(PHP 4, PHP 5, PHP 7)

dgettextOverride the current domain

Description

dgettext ( string $domain , string $message ) : string

The dgettext() function allows you to override the current domain for a single message lookup.

Parameters

domain

The domain

message

The message

Return Values

A string on success.

See Also

  • gettext() - Lookup a message in the current domain



dngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dngettextPlural version of dgettext

Description

dngettext ( string $domain , string $msgid1 , string $msgid2 , int $n ) : string

The dngettext() function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

Return Values

A string on success.

See Also



gettext

(PHP 4, PHP 5, PHP 7)

gettextLookup a message in the current domain

Description

gettext ( string $message ) : string

Looks up a message in the current domain.

Parameters

message

The message being translated.

Return Values

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Examples

Example #1 gettext()-check

<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp""./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

Notes

Note:

You may use the underscore character '_' as an alias to this function.

Note:

Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

See Also



ngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ngettextPlural version of gettext

Description

ngettext ( string $msgid1 , string $msgid2 , int $n ) : string

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parameters

msgid1

The singular message ID.

msgid2

The plural message ID.

n

The number (e.g. item count) to determine the translation for the respective grammatical number.

Return Values

Returns correct plural form of message identified by msgid1 and msgid2 for count n.

Examples

Example #1 ngettext() example

<?php

setlocale
(LC_ALL'cs_CZ');
printf(ngettext("%d window""%d windows"1), 1); // 1 okno
printf(ngettext("%d window""%d windows"2), 2); // 2 okna
printf(ngettext("%d window""%d windows"5), 5); // 5 oken

?>



textdomain

(PHP 4, PHP 5, PHP 7)

textdomainSets the default domain

Description

textdomain ( string $text_domain = NULL ) : string

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parameters

text_domain

The new message domain, or NULL to get the current setting without changing it

Return Values

If successful, this function returns the current message domain, after possibly changing it.


Table of Contents




iconv


Introduction

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the » GNU libiconv library. It will most likely end up with more consistent results.

This extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.



Installing/Configuring

Table of Contents


Requirements

You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the » libiconv library installed in your system.



Installation

This extension is enabled by default, although it may be disabled by compiling with --without-iconv.

The optional --with-iconv[=DIR] directive is used to specify the location of iconv on the system that PHP is being compiled on, otherwise only the default locations are scanned.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Iconv Configure Options
Name Default Changeable Changelog
iconv.input_encoding "" PHP_INI_ALL Deprecated in PHP 5.6.0.
iconv.output_encoding "" PHP_INI_ALL Deprecated in PHP 5.6.0.
iconv.internal_encoding "" PHP_INI_ALL Deprecated in PHP 5.6.0.

Here's a short explanation of the configuration directives.

Warning

Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.

iconv.input_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.output_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.

iconv.internal_encoding string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

PHP 5.6 and later users should leave this empty and set default_charset instead.



Resource Types

This extension has no resource types defined.




Predefined Constants

It is possible to identify at runtime which iconv implementation is adopted by this extension.
iconv implementation constants
Name Type Description
ICONV_IMPL string The implementation name
ICONV_VERSION string The implementation version

Note:

Writing implementation-dependent scripts with these constants is strongly discouraged.

The following constants are also available:
Other iconv constants
Name Type Description
ICONV_MIME_DECODE_STRICT integer A bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERROR integer A bitmask used for iconv_mime_decode()



iconv Functions

See Also

See also GNU Recode functions.


iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_get_encodingRetrieve internal configuration variables of iconv extension

Description

iconv_get_encoding ([ string $type = "all" ] ) : mixed

Retrieve internal configuration variables of iconv extension.

Parameters

type

The value of the optional type can be:

  • all
  • input_encoding
  • output_encoding
  • internal_encoding

Return Values

Returns the current value of the internal configuration variable if successful or FALSE on failure.

If type is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

Examples

Example #1 iconv_get_encoding() example

<pre>
<?php
iconv_set_encoding
("internal_encoding""UTF-8");
iconv_set_encoding("output_encoding""ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

The above example will output:

   Array
   (
       [input_encoding] => ISO-8859-1
       [output_encoding] => ISO-8859-1
       [internal_encoding] => UTF-8
   )
   
   

See Also



iconv_mime_decode_headers

(PHP 5, PHP 7)

iconv_mime_decode_headersDecodes multiple MIME header fields at once

Description

iconv_mime_decode_headers ( string $encoded_headers [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : array

Decodes multiple MIME header fields at once.

Parameters

encoded_headers

The encoded headers, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Bitmasks acceptable to iconv_mime_decode_headers()
Value Constant Description
1 ICONV_MIME_DECODE_STRICT If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 ICONV_MIME_DECODE_CONTINUE_ON_ERROR If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.

Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.

Examples

Example #1 iconv_mime_decode_headers() example

<?php
$headers_string 
= <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string0"ISO-8859-1");
print_r($headers);
?>

The above example will output:

   Array
   (
       [Subject] => Prüfung Prüfung
       [To] => example@example.com
       [Date] => Thu, 1 Jan 1970 00:00:00 +0000
       [Message-Id] => <example@example.com>
       [Received] => Array
           (
               [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
               [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
           )
   
   )
   

See Also



iconv_mime_decode

(PHP 5, PHP 7)

iconv_mime_decodeDecodes a MIME header field

Description

iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : string

Decodes a MIME header field.

Parameters

encoded_header

The encoded header, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Bitmasks acceptable to iconv_mime_decode()
Value Constant Description
1 ICONV_MIME_DECODE_STRICT If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 ICONV_MIME_DECODE_CONTINUE_ON_ERROR If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

Examples

Example #1 iconv_mime_decode() example

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       
0"ISO-8859-1");
?>

See Also



iconv_mime_encode

(PHP 5, PHP 7)

iconv_mime_encodeComposes a MIME header field

Description

iconv_mime_encode ( string $field_name , string $field_value [, array $preferences = NULL ] ) : string

Composes and returns a string that represents a valid MIME header field, which looks like the following:

   Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
   
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

Parameters

field_name

The field name.

field_value

The field value.

preferences

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.
Configuration items supported by iconv_mime_encode()
Item Type Description Default value Example
scheme string Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. B B
input-charset string Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. iconv.internal_encoding ISO-8859-1
output-charset string Specifies the character set to use to compose the MIME header. iconv.internal_encoding UTF-8
line-length integer Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. 76 996
line-break-chars string Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. \r\n \n

Return Values

Returns an encoded MIME field on success, or FALSE if an error occurs during the encoding.

Examples

Example #1 iconv_mime_encode() example

<?php
$preferences 
= array(
    
"input-charset" => "ISO-8859-1",
    
"output-charset" => "UTF-8",
    
"line-length" => 76,
    
"line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject""Prüfung Prüfung"$preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject""Prüfung Prüfung"$preferences);
?>

See Also



iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_set_encodingSet current setting for character encoding conversion

Description

iconv_set_encoding ( string $type , string $charset ) : bool

Changes the value of the internal configuration variable specified by type to charset.

Parameters

type

The value of type can be any one of these:

  • input_encoding
  • output_encoding
  • internal_encoding

charset

The character set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 iconv_set_encoding() example

<?php
iconv_set_encoding
("internal_encoding""UTF-8");
iconv_set_encoding("output_encoding""ISO-8859-1");
?>

See Also



iconv_strlen

(PHP 5, PHP 7)

iconv_strlenReturns the character count of string

Description

iconv_strlen ( string $str [, string $charset = ini_get("iconv.internal_encoding") ] ) : int

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.

Parameters

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

Return Values

Returns the character count of str, as an integer.

See Also



iconv_strpos

(PHP 5, PHP 7)

iconv_strposFinds position of first occurrence of a needle within a haystack

Description

iconv_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : int

Finds position of first occurrence of a needle within a haystack.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parameters

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed. If the offset is negative, it is counted from the end of the string.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the first occurrence of needle in haystack.

If needle is not found, iconv_strpos() will return FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version Description
7.1.0 Support for negative offsets has been added.

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • mb_strpos() - Find position of first occurrence of string in a string



iconv_strrpos

(PHP 5, PHP 7)

iconv_strrposFinds the last occurrence of a needle within a haystack

Description

iconv_strrpos ( string $haystack , string $needle [, string $charset = ini_get("iconv.internal_encoding") ] ) : int

Finds the last occurrence of a needle within a haystack.

In contrast to strrpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parameters

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Return Values

Returns the numeric position of the last occurrence of needle in haystack.

If needle is not found, iconv_strrpos() will return FALSE.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

See Also

  • strrpos() - Find the position of the last occurrence of a substring in a string
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • mb_strrpos() - Find position of last occurrence of a string in a string



iconv_substr

(PHP 5, PHP 7)

iconv_substrCut out part of a string

Description

iconv_substr ( string $str , int $offset [, int $length = iconv_strlen($str, $charset) [, string $charset = ini_get("iconv.internal_encoding") ]] ) : string

Cuts a portion of str specified by the offset and length parameters.

Parameters

str

The original string.

offset

If offset is non-negative, iconv_substr() cuts the portion out of str beginning at offset'th character, counting from zero.

If offset is negative, iconv_substr() cuts out the portion beginning at the position, offset characters away from the end of str.

length

If length is given and is positive, the return value will contain at most length characters of the portion that begins at offset (depending on the length of string).

If negative length is passed, iconv_substr() cuts the portion out of str from the offset'th character up to the character that is length characters away from the end of the string. In case offset is also negative, the start position is calculated beforehand according to the rule explained above.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset, whilst the counterpart substr() always takes these for byte offsets.

Return Values

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned. If str is exactly offset characters long, an empty string will be returned.

Changelog

Version Description
7.0.11 If str is equal to offset characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.

See Also



iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconvConvert string to requested character encoding

Description

iconv ( string $in_charset , string $out_charset , string $str ) : string

Performs a character set conversion on the string str from in_charset to out_charset.

Parameters

in_charset

The input charset.

out_charset

The output charset.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, E_NOTICE is generated and the function will return FALSE.

Caution

If and how //TRANSLIT works exactly depends on the system's iconv() implementation (cf. ICONV_IMPL). Some implementations are known to ignore //TRANSLIT, so the conversion is likely to fail for characters which are illegal for the out_charset.

str

The string to be converted.

Return Values

Returns the converted string or FALSE on failure.

Changelog

Version Description
5.4.0 Since this version, the function returns FALSE on illegal characters, unless //IGNORE is specified in output charset. Before, it returned partial output string.

Examples

Example #1 iconv() example

<?php
$text 
"This is the Euro symbol '€'.";

echo 
'Original : '$textPHP_EOL;
echo 
'TRANSLIT : 'iconv("UTF-8""ISO-8859-1//TRANSLIT"$text), PHP_EOL;
echo 
'IGNORE   : 'iconv("UTF-8""ISO-8859-1//IGNORE"$text), PHP_EOL;
echo 
'Plain    : 'iconv("UTF-8""ISO-8859-1"$text), PHP_EOL;

?>

The above example will output something similar to:

   Original : This is the Euro symbol '€'.
   TRANSLIT : This is the Euro symbol 'EUR'.
   IGNORE   : This is the Euro symbol ''.
   Plain    :
   Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
   



ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ob_iconv_handlerConvert character encoding as output buffer handler

Description

ob_iconv_handler ( string $contents , int $status ) : string

Converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined in the php.ini file or in iconv_set_encoding().

Parameters

See ob_start() for information about this handler parameters.

Return Values

See ob_start() for information about this handler return values.

Examples

Example #1 ob_iconv_handler() example:

<?php
iconv_set_encoding
("internal_encoding""UTF-8");
iconv_set_encoding("output_encoding""ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>

See Also


Table of Contents




Internationalization Functions


Introduction

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform various locale-aware operations including but not limited to formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes,

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

  • Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
  • Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
  • Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them. It can handle plurals, locale-aware numbers, currencies, conditions and much more.
  • Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
  • Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.
  • Calendar: provides a class which could be used for locale-aware calendar operations and getting various information such as timezone for locale chosen, first day of week or if it's daylight saving time now.
  • Timezone: provides a wrapper around the » "Olson" database which has information about all the timezones around the world.
  • Date formatter: allows to display date and time according to the localized format or given pattern or set of rules, and to parse strings into date and time.
  • Transliterator: allows getting latin representation of strings in various languages.


Installing/Configuring

Table of Contents


Requirements

To build the extension you need to install the » ICU library, version 4.0.0 or newer is required. As of PHP 7.4.0 ICU 50.1 or newer is required.

This extension is bundled with PHP as of PHP version 5.3.0. Alternatively, the PECL version of this extension may be used with all PHP versions greater than 5.2.0 (5.2.4+ recommended).



Installation

This extension may be installed using the bundled version as of PHP 5.3.0, or as a PECL extension as of PHP 5.2.0. In other words, there are two methods to install the intl extension.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/intl.

Alternatively, --enable-intl will enable the bundled version while compiling PHP.

If your ICU is installed to a non-standard directory then you might want to specify its location in LD_LIBRARY_PATH environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to `configure' are not needed.



Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Intl Configure Options
Name Default Changeable Changelog
intl.default_locale   PHP_INI_ALL  
intl.error_level 0 PHP_INI_ALL  
intl.use_exceptions 0 PHP_INI_ALL Available since PHP 5.5 and PECL 3.0.0a1

Here's a short explanation of the configuration directives.

intl.default_locale string

The locale that will be used in intl functions when none is specified (either by omitting the corresponding argument or by passing NULL). These are ICU locales, not system locales. The built-in ICU locales and their data can be explored at » http://demo.icu-project.org/icu-bin/locexp.

The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.

intl.error_level integer

The level of the error messages generated when an error occurs in ICU functions. This is a PHP error level, such as E_WARNING. It can be set to 0 in order to inhibit the messages. This does not affect the return values indicating error or the values returned by intl_get_error_code() or by the class specific methods for retrieving error codes and messages. Choosing E_ERROR will terminate the script whenever an error condition is found on intl classes.

The default value is 0.

intl.use_exceptions integer

If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.

The default value is FALSE.



Resource Types

This extension has no resource types defined.